block: move disk stat accounting to struct block_device
[linux-2.6-microblaze.git] / fs / block_dev.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/fs/block_dev.c
4  *
5  *  Copyright (C) 1991, 1992  Linus Torvalds
6  *  Copyright (C) 2001  Andrea Arcangeli <andrea@suse.de> SuSE
7  */
8
9 #include <linux/init.h>
10 #include <linux/mm.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/part_stat.h>
36 #include <linux/uaccess.h>
37 #include <linux/suspend.h>
38 #include "internal.h"
39
40 struct bdev_inode {
41         struct block_device bdev;
42         struct inode vfs_inode;
43 };
44
45 static const struct address_space_operations def_blk_aops;
46
47 static inline struct bdev_inode *BDEV_I(struct inode *inode)
48 {
49         return container_of(inode, struct bdev_inode, vfs_inode);
50 }
51
52 struct block_device *I_BDEV(struct inode *inode)
53 {
54         return &BDEV_I(inode)->bdev;
55 }
56 EXPORT_SYMBOL(I_BDEV);
57
58 static void bdev_write_inode(struct block_device *bdev)
59 {
60         struct inode *inode = bdev->bd_inode;
61         int ret;
62
63         spin_lock(&inode->i_lock);
64         while (inode->i_state & I_DIRTY) {
65                 spin_unlock(&inode->i_lock);
66                 ret = write_inode_now(inode, true);
67                 if (ret) {
68                         char name[BDEVNAME_SIZE];
69                         pr_warn_ratelimited("VFS: Dirty inode writeback failed "
70                                             "for block device %s (err=%d).\n",
71                                             bdevname(bdev, name), ret);
72                 }
73                 spin_lock(&inode->i_lock);
74         }
75         spin_unlock(&inode->i_lock);
76 }
77
78 /* Kill _all_ buffers and pagecache , dirty or not.. */
79 static void kill_bdev(struct block_device *bdev)
80 {
81         struct address_space *mapping = bdev->bd_inode->i_mapping;
82
83         if (mapping->nrpages == 0 && mapping->nrexceptional == 0)
84                 return;
85
86         invalidate_bh_lrus();
87         truncate_inode_pages(mapping, 0);
88 }
89
90 /* Invalidate clean unused buffers and pagecache. */
91 void invalidate_bdev(struct block_device *bdev)
92 {
93         struct address_space *mapping = bdev->bd_inode->i_mapping;
94
95         if (mapping->nrpages) {
96                 invalidate_bh_lrus();
97                 lru_add_drain_all();    /* make sure all lru add caches are flushed */
98                 invalidate_mapping_pages(mapping, 0, -1);
99         }
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
102          */
103         cleancache_invalidate_inode(mapping);
104 }
105 EXPORT_SYMBOL(invalidate_bdev);
106
107 /*
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).
110  */
111 int truncate_bdev_range(struct block_device *bdev, fmode_t mode,
112                         loff_t lstart, loff_t lend)
113 {
114         /*
115          * If we don't hold exclusive handle for the device, upgrade to it
116          * while we discard the buffer cache to avoid discarding buffers
117          * under live filesystem.
118          */
119         if (!(mode & FMODE_EXCL)) {
120                 int err = bd_prepare_to_claim(bdev, truncate_bdev_range);
121                 if (err)
122                         return err;
123         }
124
125         truncate_inode_pages_range(bdev->bd_inode->i_mapping, lstart, lend);
126         if (!(mode & FMODE_EXCL))
127                 bd_abort_claiming(bdev, truncate_bdev_range);
128         return 0;
129 }
130 EXPORT_SYMBOL(truncate_bdev_range);
131
132 static void set_init_blocksize(struct block_device *bdev)
133 {
134         bdev->bd_inode->i_blkbits = blksize_bits(bdev_logical_block_size(bdev));
135 }
136
137 int set_blocksize(struct block_device *bdev, int size)
138 {
139         /* Size must be a power of two, and between 512 and PAGE_SIZE */
140         if (size > PAGE_SIZE || size < 512 || !is_power_of_2(size))
141                 return -EINVAL;
142
143         /* Size cannot be smaller than the size supported by the device */
144         if (size < bdev_logical_block_size(bdev))
145                 return -EINVAL;
146
147         /* Don't change the size if it is same as current */
148         if (bdev->bd_inode->i_blkbits != blksize_bits(size)) {
149                 sync_blockdev(bdev);
150                 bdev->bd_inode->i_blkbits = blksize_bits(size);
151                 kill_bdev(bdev);
152         }
153         return 0;
154 }
155
156 EXPORT_SYMBOL(set_blocksize);
157
158 int sb_set_blocksize(struct super_block *sb, int size)
159 {
160         if (set_blocksize(sb->s_bdev, size))
161                 return 0;
162         /* If we get here, we know size is power of two
163          * and it's value is between 512 and PAGE_SIZE */
164         sb->s_blocksize = size;
165         sb->s_blocksize_bits = blksize_bits(size);
166         return sb->s_blocksize;
167 }
168
169 EXPORT_SYMBOL(sb_set_blocksize);
170
171 int sb_min_blocksize(struct super_block *sb, int size)
172 {
173         int minsize = bdev_logical_block_size(sb->s_bdev);
174         if (size < minsize)
175                 size = minsize;
176         return sb_set_blocksize(sb, size);
177 }
178
179 EXPORT_SYMBOL(sb_min_blocksize);
180
181 static int
182 blkdev_get_block(struct inode *inode, sector_t iblock,
183                 struct buffer_head *bh, int create)
184 {
185         bh->b_bdev = I_BDEV(inode);
186         bh->b_blocknr = iblock;
187         set_buffer_mapped(bh);
188         return 0;
189 }
190
191 static struct inode *bdev_file_inode(struct file *file)
192 {
193         return file->f_mapping->host;
194 }
195
196 static unsigned int dio_bio_write_op(struct kiocb *iocb)
197 {
198         unsigned int op = REQ_OP_WRITE | REQ_SYNC | REQ_IDLE;
199
200         /* avoid the need for a I/O completion work item */
201         if (iocb->ki_flags & IOCB_DSYNC)
202                 op |= REQ_FUA;
203         return op;
204 }
205
206 #define DIO_INLINE_BIO_VECS 4
207
208 static void blkdev_bio_end_io_simple(struct bio *bio)
209 {
210         struct task_struct *waiter = bio->bi_private;
211
212         WRITE_ONCE(bio->bi_private, NULL);
213         blk_wake_io_task(waiter);
214 }
215
216 static ssize_t
217 __blkdev_direct_IO_simple(struct kiocb *iocb, struct iov_iter *iter,
218                 int nr_pages)
219 {
220         struct file *file = iocb->ki_filp;
221         struct block_device *bdev = I_BDEV(bdev_file_inode(file));
222         struct bio_vec inline_vecs[DIO_INLINE_BIO_VECS], *vecs;
223         loff_t pos = iocb->ki_pos;
224         bool should_dirty = false;
225         struct bio bio;
226         ssize_t ret;
227         blk_qc_t qc;
228
229         if ((pos | iov_iter_alignment(iter)) &
230             (bdev_logical_block_size(bdev) - 1))
231                 return -EINVAL;
232
233         if (nr_pages <= DIO_INLINE_BIO_VECS)
234                 vecs = inline_vecs;
235         else {
236                 vecs = kmalloc_array(nr_pages, sizeof(struct bio_vec),
237                                      GFP_KERNEL);
238                 if (!vecs)
239                         return -ENOMEM;
240         }
241
242         bio_init(&bio, vecs, nr_pages);
243         bio_set_dev(&bio, bdev);
244         bio.bi_iter.bi_sector = pos >> 9;
245         bio.bi_write_hint = iocb->ki_hint;
246         bio.bi_private = current;
247         bio.bi_end_io = blkdev_bio_end_io_simple;
248         bio.bi_ioprio = iocb->ki_ioprio;
249
250         ret = bio_iov_iter_get_pages(&bio, iter);
251         if (unlikely(ret))
252                 goto out;
253         ret = bio.bi_iter.bi_size;
254
255         if (iov_iter_rw(iter) == READ) {
256                 bio.bi_opf = REQ_OP_READ;
257                 if (iter_is_iovec(iter))
258                         should_dirty = true;
259         } else {
260                 bio.bi_opf = dio_bio_write_op(iocb);
261                 task_io_account_write(ret);
262         }
263         if (iocb->ki_flags & IOCB_HIPRI)
264                 bio_set_polled(&bio, iocb);
265
266         qc = submit_bio(&bio);
267         for (;;) {
268                 set_current_state(TASK_UNINTERRUPTIBLE);
269                 if (!READ_ONCE(bio.bi_private))
270                         break;
271                 if (!(iocb->ki_flags & IOCB_HIPRI) ||
272                     !blk_poll(bdev_get_queue(bdev), qc, true))
273                         blk_io_schedule();
274         }
275         __set_current_state(TASK_RUNNING);
276
277         bio_release_pages(&bio, should_dirty);
278         if (unlikely(bio.bi_status))
279                 ret = blk_status_to_errno(bio.bi_status);
280
281 out:
282         if (vecs != inline_vecs)
283                 kfree(vecs);
284
285         bio_uninit(&bio);
286
287         return ret;
288 }
289
290 struct blkdev_dio {
291         union {
292                 struct kiocb            *iocb;
293                 struct task_struct      *waiter;
294         };
295         size_t                  size;
296         atomic_t                ref;
297         bool                    multi_bio : 1;
298         bool                    should_dirty : 1;
299         bool                    is_sync : 1;
300         struct bio              bio;
301 };
302
303 static struct bio_set blkdev_dio_pool;
304
305 static int blkdev_iopoll(struct kiocb *kiocb, bool wait)
306 {
307         struct block_device *bdev = I_BDEV(kiocb->ki_filp->f_mapping->host);
308         struct request_queue *q = bdev_get_queue(bdev);
309
310         return blk_poll(q, READ_ONCE(kiocb->ki_cookie), wait);
311 }
312
313 static void blkdev_bio_end_io(struct bio *bio)
314 {
315         struct blkdev_dio *dio = bio->bi_private;
316         bool should_dirty = dio->should_dirty;
317
318         if (bio->bi_status && !dio->bio.bi_status)
319                 dio->bio.bi_status = bio->bi_status;
320
321         if (!dio->multi_bio || atomic_dec_and_test(&dio->ref)) {
322                 if (!dio->is_sync) {
323                         struct kiocb *iocb = dio->iocb;
324                         ssize_t ret;
325
326                         if (likely(!dio->bio.bi_status)) {
327                                 ret = dio->size;
328                                 iocb->ki_pos += ret;
329                         } else {
330                                 ret = blk_status_to_errno(dio->bio.bi_status);
331                         }
332
333                         dio->iocb->ki_complete(iocb, ret, 0);
334                         if (dio->multi_bio)
335                                 bio_put(&dio->bio);
336                 } else {
337                         struct task_struct *waiter = dio->waiter;
338
339                         WRITE_ONCE(dio->waiter, NULL);
340                         blk_wake_io_task(waiter);
341                 }
342         }
343
344         if (should_dirty) {
345                 bio_check_pages_dirty(bio);
346         } else {
347                 bio_release_pages(bio, false);
348                 bio_put(bio);
349         }
350 }
351
352 static ssize_t
353 __blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter, int nr_pages)
354 {
355         struct file *file = iocb->ki_filp;
356         struct inode *inode = bdev_file_inode(file);
357         struct block_device *bdev = I_BDEV(inode);
358         struct blk_plug plug;
359         struct blkdev_dio *dio;
360         struct bio *bio;
361         bool is_poll = (iocb->ki_flags & IOCB_HIPRI) != 0;
362         bool is_read = (iov_iter_rw(iter) == READ), is_sync;
363         loff_t pos = iocb->ki_pos;
364         blk_qc_t qc = BLK_QC_T_NONE;
365         int ret = 0;
366
367         if ((pos | iov_iter_alignment(iter)) &
368             (bdev_logical_block_size(bdev) - 1))
369                 return -EINVAL;
370
371         bio = bio_alloc_bioset(GFP_KERNEL, nr_pages, &blkdev_dio_pool);
372
373         dio = container_of(bio, struct blkdev_dio, bio);
374         dio->is_sync = is_sync = is_sync_kiocb(iocb);
375         if (dio->is_sync) {
376                 dio->waiter = current;
377                 bio_get(bio);
378         } else {
379                 dio->iocb = iocb;
380         }
381
382         dio->size = 0;
383         dio->multi_bio = false;
384         dio->should_dirty = is_read && iter_is_iovec(iter);
385
386         /*
387          * Don't plug for HIPRI/polled IO, as those should go straight
388          * to issue
389          */
390         if (!is_poll)
391                 blk_start_plug(&plug);
392
393         for (;;) {
394                 bio_set_dev(bio, bdev);
395                 bio->bi_iter.bi_sector = pos >> 9;
396                 bio->bi_write_hint = iocb->ki_hint;
397                 bio->bi_private = dio;
398                 bio->bi_end_io = blkdev_bio_end_io;
399                 bio->bi_ioprio = iocb->ki_ioprio;
400
401                 ret = bio_iov_iter_get_pages(bio, iter);
402                 if (unlikely(ret)) {
403                         bio->bi_status = BLK_STS_IOERR;
404                         bio_endio(bio);
405                         break;
406                 }
407
408                 if (is_read) {
409                         bio->bi_opf = REQ_OP_READ;
410                         if (dio->should_dirty)
411                                 bio_set_pages_dirty(bio);
412                 } else {
413                         bio->bi_opf = dio_bio_write_op(iocb);
414                         task_io_account_write(bio->bi_iter.bi_size);
415                 }
416
417                 dio->size += bio->bi_iter.bi_size;
418                 pos += bio->bi_iter.bi_size;
419
420                 nr_pages = iov_iter_npages(iter, BIO_MAX_PAGES);
421                 if (!nr_pages) {
422                         bool polled = false;
423
424                         if (iocb->ki_flags & IOCB_HIPRI) {
425                                 bio_set_polled(bio, iocb);
426                                 polled = true;
427                         }
428
429                         qc = submit_bio(bio);
430
431                         if (polled)
432                                 WRITE_ONCE(iocb->ki_cookie, qc);
433                         break;
434                 }
435
436                 if (!dio->multi_bio) {
437                         /*
438                          * AIO needs an extra reference to ensure the dio
439                          * structure which is embedded into the first bio
440                          * stays around.
441                          */
442                         if (!is_sync)
443                                 bio_get(bio);
444                         dio->multi_bio = true;
445                         atomic_set(&dio->ref, 2);
446                 } else {
447                         atomic_inc(&dio->ref);
448                 }
449
450                 submit_bio(bio);
451                 bio = bio_alloc(GFP_KERNEL, nr_pages);
452         }
453
454         if (!is_poll)
455                 blk_finish_plug(&plug);
456
457         if (!is_sync)
458                 return -EIOCBQUEUED;
459
460         for (;;) {
461                 set_current_state(TASK_UNINTERRUPTIBLE);
462                 if (!READ_ONCE(dio->waiter))
463                         break;
464
465                 if (!(iocb->ki_flags & IOCB_HIPRI) ||
466                     !blk_poll(bdev_get_queue(bdev), qc, true))
467                         blk_io_schedule();
468         }
469         __set_current_state(TASK_RUNNING);
470
471         if (!ret)
472                 ret = blk_status_to_errno(dio->bio.bi_status);
473         if (likely(!ret))
474                 ret = dio->size;
475
476         bio_put(&dio->bio);
477         return ret;
478 }
479
480 static ssize_t
481 blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
482 {
483         int nr_pages;
484
485         nr_pages = iov_iter_npages(iter, BIO_MAX_PAGES + 1);
486         if (!nr_pages)
487                 return 0;
488         if (is_sync_kiocb(iocb) && nr_pages <= BIO_MAX_PAGES)
489                 return __blkdev_direct_IO_simple(iocb, iter, nr_pages);
490
491         return __blkdev_direct_IO(iocb, iter, min(nr_pages, BIO_MAX_PAGES));
492 }
493
494 static __init int blkdev_init(void)
495 {
496         return bioset_init(&blkdev_dio_pool, 4, offsetof(struct blkdev_dio, bio), BIOSET_NEED_BVECS);
497 }
498 module_init(blkdev_init);
499
500 int __sync_blockdev(struct block_device *bdev, int wait)
501 {
502         if (!bdev)
503                 return 0;
504         if (!wait)
505                 return filemap_flush(bdev->bd_inode->i_mapping);
506         return filemap_write_and_wait(bdev->bd_inode->i_mapping);
507 }
508
509 /*
510  * Write out and wait upon all the dirty data associated with a block
511  * device via its mapping.  Does not take the superblock lock.
512  */
513 int sync_blockdev(struct block_device *bdev)
514 {
515         return __sync_blockdev(bdev, 1);
516 }
517 EXPORT_SYMBOL(sync_blockdev);
518
519 /*
520  * Write out and wait upon all dirty data associated with this
521  * device.   Filesystem data as well as the underlying block
522  * device.  Takes the superblock lock.
523  */
524 int fsync_bdev(struct block_device *bdev)
525 {
526         struct super_block *sb = get_super(bdev);
527         if (sb) {
528                 int res = sync_filesystem(sb);
529                 drop_super(sb);
530                 return res;
531         }
532         return sync_blockdev(bdev);
533 }
534 EXPORT_SYMBOL(fsync_bdev);
535
536 /**
537  * freeze_bdev  --  lock a filesystem and force it into a consistent state
538  * @bdev:       blockdevice to lock
539  *
540  * If a superblock is found on this device, we take the s_umount semaphore
541  * on it to make sure nobody unmounts until the snapshot creation is done.
542  * The reference counter (bd_fsfreeze_count) guarantees that only the last
543  * unfreeze process can unfreeze the frozen filesystem actually when multiple
544  * freeze requests arrive simultaneously. It counts up in freeze_bdev() and
545  * count down in thaw_bdev(). When it becomes 0, thaw_bdev() will unfreeze
546  * actually.
547  */
548 int freeze_bdev(struct block_device *bdev)
549 {
550         struct super_block *sb;
551         int error = 0;
552
553         mutex_lock(&bdev->bd_fsfreeze_mutex);
554         if (++bdev->bd_fsfreeze_count > 1)
555                 goto done;
556
557         sb = get_active_super(bdev);
558         if (!sb)
559                 goto sync;
560         if (sb->s_op->freeze_super)
561                 error = sb->s_op->freeze_super(sb);
562         else
563                 error = freeze_super(sb);
564         deactivate_super(sb);
565
566         if (error) {
567                 bdev->bd_fsfreeze_count--;
568                 goto done;
569         }
570         bdev->bd_fsfreeze_sb = sb;
571
572 sync:
573         sync_blockdev(bdev);
574 done:
575         mutex_unlock(&bdev->bd_fsfreeze_mutex);
576         return error;
577 }
578 EXPORT_SYMBOL(freeze_bdev);
579
580 /**
581  * thaw_bdev  -- unlock filesystem
582  * @bdev:       blockdevice to unlock
583  *
584  * Unlocks the filesystem and marks it writeable again after freeze_bdev().
585  */
586 int thaw_bdev(struct block_device *bdev)
587 {
588         struct super_block *sb;
589         int error = -EINVAL;
590
591         mutex_lock(&bdev->bd_fsfreeze_mutex);
592         if (!bdev->bd_fsfreeze_count)
593                 goto out;
594
595         error = 0;
596         if (--bdev->bd_fsfreeze_count > 0)
597                 goto out;
598
599         sb = bdev->bd_fsfreeze_sb;
600         if (!sb)
601                 goto out;
602
603         if (sb->s_op->thaw_super)
604                 error = sb->s_op->thaw_super(sb);
605         else
606                 error = thaw_super(sb);
607         if (error)
608                 bdev->bd_fsfreeze_count++;
609 out:
610         mutex_unlock(&bdev->bd_fsfreeze_mutex);
611         return error;
612 }
613 EXPORT_SYMBOL(thaw_bdev);
614
615 static int blkdev_writepage(struct page *page, struct writeback_control *wbc)
616 {
617         return block_write_full_page(page, blkdev_get_block, wbc);
618 }
619
620 static int blkdev_readpage(struct file * file, struct page * page)
621 {
622         return block_read_full_page(page, blkdev_get_block);
623 }
624
625 static void blkdev_readahead(struct readahead_control *rac)
626 {
627         mpage_readahead(rac, blkdev_get_block);
628 }
629
630 static int blkdev_write_begin(struct file *file, struct address_space *mapping,
631                         loff_t pos, unsigned len, unsigned flags,
632                         struct page **pagep, void **fsdata)
633 {
634         return block_write_begin(mapping, pos, len, flags, pagep,
635                                  blkdev_get_block);
636 }
637
638 static int blkdev_write_end(struct file *file, struct address_space *mapping,
639                         loff_t pos, unsigned len, unsigned copied,
640                         struct page *page, void *fsdata)
641 {
642         int ret;
643         ret = block_write_end(file, mapping, pos, len, copied, page, fsdata);
644
645         unlock_page(page);
646         put_page(page);
647
648         return ret;
649 }
650
651 /*
652  * private llseek:
653  * for a block special file file_inode(file)->i_size is zero
654  * so we compute the size by hand (just as in block_read/write above)
655  */
656 static loff_t block_llseek(struct file *file, loff_t offset, int whence)
657 {
658         struct inode *bd_inode = bdev_file_inode(file);
659         loff_t retval;
660
661         inode_lock(bd_inode);
662         retval = fixed_size_llseek(file, offset, whence, i_size_read(bd_inode));
663         inode_unlock(bd_inode);
664         return retval;
665 }
666         
667 int blkdev_fsync(struct file *filp, loff_t start, loff_t end, int datasync)
668 {
669         struct inode *bd_inode = bdev_file_inode(filp);
670         struct block_device *bdev = I_BDEV(bd_inode);
671         int error;
672         
673         error = file_write_and_wait_range(filp, start, end);
674         if (error)
675                 return error;
676
677         /*
678          * There is no need to serialise calls to blkdev_issue_flush with
679          * i_mutex and doing so causes performance issues with concurrent
680          * O_SYNC writers to a block device.
681          */
682         error = blkdev_issue_flush(bdev, GFP_KERNEL);
683         if (error == -EOPNOTSUPP)
684                 error = 0;
685
686         return error;
687 }
688 EXPORT_SYMBOL(blkdev_fsync);
689
690 /**
691  * bdev_read_page() - Start reading a page from a block device
692  * @bdev: The device to read the page from
693  * @sector: The offset on the device to read the page to (need not be aligned)
694  * @page: The page to read
695  *
696  * On entry, the page should be locked.  It will be unlocked when the page
697  * has been read.  If the block driver implements rw_page synchronously,
698  * that will be true on exit from this function, but it need not be.
699  *
700  * Errors returned by this function are usually "soft", eg out of memory, or
701  * queue full; callers should try a different route to read this page rather
702  * than propagate an error back up the stack.
703  *
704  * Return: negative errno if an error occurs, 0 if submission was successful.
705  */
706 int bdev_read_page(struct block_device *bdev, sector_t sector,
707                         struct page *page)
708 {
709         const struct block_device_operations *ops = bdev->bd_disk->fops;
710         int result = -EOPNOTSUPP;
711
712         if (!ops->rw_page || bdev_get_integrity(bdev))
713                 return result;
714
715         result = blk_queue_enter(bdev->bd_disk->queue, 0);
716         if (result)
717                 return result;
718         result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
719                               REQ_OP_READ);
720         blk_queue_exit(bdev->bd_disk->queue);
721         return result;
722 }
723
724 /**
725  * bdev_write_page() - Start writing a page to a block device
726  * @bdev: The device to write the page to
727  * @sector: The offset on the device to write the page to (need not be aligned)
728  * @page: The page to write
729  * @wbc: The writeback_control for the write
730  *
731  * On entry, the page should be locked and not currently under writeback.
732  * On exit, if the write started successfully, the page will be unlocked and
733  * under writeback.  If the write failed already (eg the driver failed to
734  * queue the page to the device), the page will still be locked.  If the
735  * caller is a ->writepage implementation, it will need to unlock the page.
736  *
737  * Errors returned by this function are usually "soft", eg out of memory, or
738  * queue full; callers should try a different route to write this page rather
739  * than propagate an error back up the stack.
740  *
741  * Return: negative errno if an error occurs, 0 if submission was successful.
742  */
743 int bdev_write_page(struct block_device *bdev, sector_t sector,
744                         struct page *page, struct writeback_control *wbc)
745 {
746         int result;
747         const struct block_device_operations *ops = bdev->bd_disk->fops;
748
749         if (!ops->rw_page || bdev_get_integrity(bdev))
750                 return -EOPNOTSUPP;
751         result = blk_queue_enter(bdev->bd_disk->queue, 0);
752         if (result)
753                 return result;
754
755         set_page_writeback(page);
756         result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
757                               REQ_OP_WRITE);
758         if (result) {
759                 end_page_writeback(page);
760         } else {
761                 clean_page_buffers(page);
762                 unlock_page(page);
763         }
764         blk_queue_exit(bdev->bd_disk->queue);
765         return result;
766 }
767
768 /*
769  * pseudo-fs
770  */
771
772 static  __cacheline_aligned_in_smp DEFINE_SPINLOCK(bdev_lock);
773 static struct kmem_cache * bdev_cachep __read_mostly;
774
775 static struct inode *bdev_alloc_inode(struct super_block *sb)
776 {
777         struct bdev_inode *ei = kmem_cache_alloc(bdev_cachep, GFP_KERNEL);
778         if (!ei)
779                 return NULL;
780         return &ei->vfs_inode;
781 }
782
783 static void bdev_free_inode(struct inode *inode)
784 {
785         struct block_device *bdev = I_BDEV(inode);
786
787         free_percpu(bdev->bd_stats);
788
789         kmem_cache_free(bdev_cachep, BDEV_I(inode));
790 }
791
792 static void init_once(void *data)
793 {
794         struct bdev_inode *ei = data;
795
796         inode_init_once(&ei->vfs_inode);
797 }
798
799 static void bdev_evict_inode(struct inode *inode)
800 {
801         struct block_device *bdev = &BDEV_I(inode)->bdev;
802         truncate_inode_pages_final(&inode->i_data);
803         invalidate_inode_buffers(inode); /* is it needed here? */
804         clear_inode(inode);
805         /* Detach inode from wb early as bdi_put() may free bdi->wb */
806         inode_detach_wb(inode);
807         if (bdev->bd_bdi != &noop_backing_dev_info) {
808                 bdi_put(bdev->bd_bdi);
809                 bdev->bd_bdi = &noop_backing_dev_info;
810         }
811 }
812
813 static const struct super_operations bdev_sops = {
814         .statfs = simple_statfs,
815         .alloc_inode = bdev_alloc_inode,
816         .free_inode = bdev_free_inode,
817         .drop_inode = generic_delete_inode,
818         .evict_inode = bdev_evict_inode,
819 };
820
821 static int bd_init_fs_context(struct fs_context *fc)
822 {
823         struct pseudo_fs_context *ctx = init_pseudo(fc, BDEVFS_MAGIC);
824         if (!ctx)
825                 return -ENOMEM;
826         fc->s_iflags |= SB_I_CGROUPWB;
827         ctx->ops = &bdev_sops;
828         return 0;
829 }
830
831 static struct file_system_type bd_type = {
832         .name           = "bdev",
833         .init_fs_context = bd_init_fs_context,
834         .kill_sb        = kill_anon_super,
835 };
836
837 struct super_block *blockdev_superblock __read_mostly;
838 EXPORT_SYMBOL_GPL(blockdev_superblock);
839
840 void __init bdev_cache_init(void)
841 {
842         int err;
843         static struct vfsmount *bd_mnt;
844
845         bdev_cachep = kmem_cache_create("bdev_cache", sizeof(struct bdev_inode),
846                         0, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
847                                 SLAB_MEM_SPREAD|SLAB_ACCOUNT|SLAB_PANIC),
848                         init_once);
849         err = register_filesystem(&bd_type);
850         if (err)
851                 panic("Cannot register bdev pseudo-fs");
852         bd_mnt = kern_mount(&bd_type);
853         if (IS_ERR(bd_mnt))
854                 panic("Cannot create bdev pseudo-fs");
855         blockdev_superblock = bd_mnt->mnt_sb;   /* For writeback */
856 }
857
858 struct block_device *bdev_alloc(struct gendisk *disk, u8 partno)
859 {
860         struct block_device *bdev;
861         struct inode *inode;
862
863         inode = new_inode(blockdev_superblock);
864         if (!inode)
865                 return NULL;
866         inode->i_mode = S_IFBLK;
867         inode->i_rdev = 0;
868         inode->i_data.a_ops = &def_blk_aops;
869         mapping_set_gfp_mask(&inode->i_data, GFP_USER);
870
871         bdev = I_BDEV(inode);
872         memset(bdev, 0, sizeof(*bdev));
873         mutex_init(&bdev->bd_mutex);
874         mutex_init(&bdev->bd_fsfreeze_mutex);
875         spin_lock_init(&bdev->bd_size_lock);
876         bdev->bd_disk = disk;
877         bdev->bd_partno = partno;
878         bdev->bd_inode = inode;
879         bdev->bd_bdi = &noop_backing_dev_info;
880 #ifdef CONFIG_SYSFS
881         INIT_LIST_HEAD(&bdev->bd_holder_disks);
882 #endif
883         bdev->bd_stats = alloc_percpu(struct disk_stats);
884         if (!bdev->bd_stats) {
885                 iput(inode);
886                 return NULL;
887         }
888         return bdev;
889 }
890
891 void bdev_add(struct block_device *bdev, dev_t dev)
892 {
893         bdev->bd_dev = dev;
894         bdev->bd_inode->i_rdev = dev;
895         bdev->bd_inode->i_ino = dev;
896         insert_inode_hash(bdev->bd_inode);
897 }
898
899 static struct block_device *bdget(dev_t dev)
900 {
901         struct inode *inode;
902
903         inode = ilookup(blockdev_superblock, dev);
904         if (!inode)
905                 return NULL;
906         return &BDEV_I(inode)->bdev;
907 }
908
909 /**
910  * bdgrab -- Grab a reference to an already referenced block device
911  * @bdev:       Block device to grab a reference to.
912  *
913  * Returns the block_device with an additional reference when successful,
914  * or NULL if the inode is already beeing freed.
915  */
916 struct block_device *bdgrab(struct block_device *bdev)
917 {
918         if (!igrab(bdev->bd_inode))
919                 return NULL;
920         return bdev;
921 }
922 EXPORT_SYMBOL(bdgrab);
923
924 struct block_device *bdget_part(struct hd_struct *part)
925 {
926         return bdget(part_devt(part));
927 }
928
929 long nr_blockdev_pages(void)
930 {
931         struct inode *inode;
932         long ret = 0;
933
934         spin_lock(&blockdev_superblock->s_inode_list_lock);
935         list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list)
936                 ret += inode->i_mapping->nrpages;
937         spin_unlock(&blockdev_superblock->s_inode_list_lock);
938
939         return ret;
940 }
941
942 void bdput(struct block_device *bdev)
943 {
944         iput(bdev->bd_inode);
945 }
946 EXPORT_SYMBOL(bdput);
947  
948 /**
949  * bd_may_claim - test whether a block device can be claimed
950  * @bdev: block device of interest
951  * @whole: whole block device containing @bdev, may equal @bdev
952  * @holder: holder trying to claim @bdev
953  *
954  * Test whether @bdev can be claimed by @holder.
955  *
956  * CONTEXT:
957  * spin_lock(&bdev_lock).
958  *
959  * RETURNS:
960  * %true if @bdev can be claimed, %false otherwise.
961  */
962 static bool bd_may_claim(struct block_device *bdev, struct block_device *whole,
963                          void *holder)
964 {
965         if (bdev->bd_holder == holder)
966                 return true;     /* already a holder */
967         else if (bdev->bd_holder != NULL)
968                 return false;    /* held by someone else */
969         else if (whole == bdev)
970                 return true;     /* is a whole device which isn't held */
971
972         else if (whole->bd_holder == bd_may_claim)
973                 return true;     /* is a partition of a device that is being partitioned */
974         else if (whole->bd_holder != NULL)
975                 return false;    /* is a partition of a held device */
976         else
977                 return true;     /* is a partition of an un-held device */
978 }
979
980 /**
981  * bd_prepare_to_claim - claim a block device
982  * @bdev: block device of interest
983  * @holder: holder trying to claim @bdev
984  *
985  * Claim @bdev.  This function fails if @bdev is already claimed by another
986  * holder and waits if another claiming is in progress. return, the caller
987  * has ownership of bd_claiming and bd_holder[s].
988  *
989  * RETURNS:
990  * 0 if @bdev can be claimed, -EBUSY otherwise.
991  */
992 int bd_prepare_to_claim(struct block_device *bdev, void *holder)
993 {
994         struct block_device *whole = bdev_whole(bdev);
995
996         if (WARN_ON_ONCE(!holder))
997                 return -EINVAL;
998 retry:
999         spin_lock(&bdev_lock);
1000         /* if someone else claimed, fail */
1001         if (!bd_may_claim(bdev, whole, holder)) {
1002                 spin_unlock(&bdev_lock);
1003                 return -EBUSY;
1004         }
1005
1006         /* if claiming is already in progress, wait for it to finish */
1007         if (whole->bd_claiming) {
1008                 wait_queue_head_t *wq = bit_waitqueue(&whole->bd_claiming, 0);
1009                 DEFINE_WAIT(wait);
1010
1011                 prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
1012                 spin_unlock(&bdev_lock);
1013                 schedule();
1014                 finish_wait(wq, &wait);
1015                 goto retry;
1016         }
1017
1018         /* yay, all mine */
1019         whole->bd_claiming = holder;
1020         spin_unlock(&bdev_lock);
1021         return 0;
1022 }
1023 EXPORT_SYMBOL_GPL(bd_prepare_to_claim); /* only for the loop driver */
1024
1025 static void bd_clear_claiming(struct block_device *whole, void *holder)
1026 {
1027         lockdep_assert_held(&bdev_lock);
1028         /* tell others that we're done */
1029         BUG_ON(whole->bd_claiming != holder);
1030         whole->bd_claiming = NULL;
1031         wake_up_bit(&whole->bd_claiming, 0);
1032 }
1033
1034 /**
1035  * bd_finish_claiming - finish claiming of a block device
1036  * @bdev: block device of interest
1037  * @holder: holder that has claimed @bdev
1038  *
1039  * Finish exclusive open of a block device. Mark the device as exlusively
1040  * open by the holder and wake up all waiters for exclusive open to finish.
1041  */
1042 static void bd_finish_claiming(struct block_device *bdev, void *holder)
1043 {
1044         struct block_device *whole = bdev_whole(bdev);
1045
1046         spin_lock(&bdev_lock);
1047         BUG_ON(!bd_may_claim(bdev, whole, holder));
1048         /*
1049          * Note that for a whole device bd_holders will be incremented twice,
1050          * and bd_holder will be set to bd_may_claim before being set to holder
1051          */
1052         whole->bd_holders++;
1053         whole->bd_holder = bd_may_claim;
1054         bdev->bd_holders++;
1055         bdev->bd_holder = holder;
1056         bd_clear_claiming(whole, holder);
1057         spin_unlock(&bdev_lock);
1058 }
1059
1060 /**
1061  * bd_abort_claiming - abort claiming of a block device
1062  * @bdev: block device of interest
1063  * @whole: whole block device
1064  * @holder: holder that has claimed @bdev
1065  *
1066  * Abort claiming of a block device when the exclusive open failed. This can be
1067  * also used when exclusive open is not actually desired and we just needed
1068  * to block other exclusive openers for a while.
1069  */
1070 void bd_abort_claiming(struct block_device *bdev, void *holder)
1071 {
1072         spin_lock(&bdev_lock);
1073         bd_clear_claiming(bdev_whole(bdev), holder);
1074         spin_unlock(&bdev_lock);
1075 }
1076 EXPORT_SYMBOL(bd_abort_claiming);
1077
1078 #ifdef CONFIG_SYSFS
1079 struct bd_holder_disk {
1080         struct list_head        list;
1081         struct gendisk          *disk;
1082         int                     refcnt;
1083 };
1084
1085 static struct bd_holder_disk *bd_find_holder_disk(struct block_device *bdev,
1086                                                   struct gendisk *disk)
1087 {
1088         struct bd_holder_disk *holder;
1089
1090         list_for_each_entry(holder, &bdev->bd_holder_disks, list)
1091                 if (holder->disk == disk)
1092                         return holder;
1093         return NULL;
1094 }
1095
1096 static int add_symlink(struct kobject *from, struct kobject *to)
1097 {
1098         return sysfs_create_link(from, to, kobject_name(to));
1099 }
1100
1101 static void del_symlink(struct kobject *from, struct kobject *to)
1102 {
1103         sysfs_remove_link(from, kobject_name(to));
1104 }
1105
1106 /**
1107  * bd_link_disk_holder - create symlinks between holding disk and slave bdev
1108  * @bdev: the claimed slave bdev
1109  * @disk: the holding disk
1110  *
1111  * DON'T USE THIS UNLESS YOU'RE ALREADY USING IT.
1112  *
1113  * This functions creates the following sysfs symlinks.
1114  *
1115  * - from "slaves" directory of the holder @disk to the claimed @bdev
1116  * - from "holders" directory of the @bdev to the holder @disk
1117  *
1118  * For example, if /dev/dm-0 maps to /dev/sda and disk for dm-0 is
1119  * passed to bd_link_disk_holder(), then:
1120  *
1121  *   /sys/block/dm-0/slaves/sda --> /sys/block/sda
1122  *   /sys/block/sda/holders/dm-0 --> /sys/block/dm-0
1123  *
1124  * The caller must have claimed @bdev before calling this function and
1125  * ensure that both @bdev and @disk are valid during the creation and
1126  * lifetime of these symlinks.
1127  *
1128  * CONTEXT:
1129  * Might sleep.
1130  *
1131  * RETURNS:
1132  * 0 on success, -errno on failure.
1133  */
1134 int bd_link_disk_holder(struct block_device *bdev, struct gendisk *disk)
1135 {
1136         struct bd_holder_disk *holder;
1137         int ret = 0;
1138
1139         mutex_lock(&bdev->bd_mutex);
1140
1141         WARN_ON_ONCE(!bdev->bd_holder);
1142
1143         /* FIXME: remove the following once add_disk() handles errors */
1144         if (WARN_ON(!disk->slave_dir || !bdev->bd_part->holder_dir))
1145                 goto out_unlock;
1146
1147         holder = bd_find_holder_disk(bdev, disk);
1148         if (holder) {
1149                 holder->refcnt++;
1150                 goto out_unlock;
1151         }
1152
1153         holder = kzalloc(sizeof(*holder), GFP_KERNEL);
1154         if (!holder) {
1155                 ret = -ENOMEM;
1156                 goto out_unlock;
1157         }
1158
1159         INIT_LIST_HEAD(&holder->list);
1160         holder->disk = disk;
1161         holder->refcnt = 1;
1162
1163         ret = add_symlink(disk->slave_dir, bdev_kobj(bdev));
1164         if (ret)
1165                 goto out_free;
1166
1167         ret = add_symlink(bdev->bd_part->holder_dir, &disk_to_dev(disk)->kobj);
1168         if (ret)
1169                 goto out_del;
1170         /*
1171          * bdev could be deleted beneath us which would implicitly destroy
1172          * the holder directory.  Hold on to it.
1173          */
1174         kobject_get(bdev->bd_part->holder_dir);
1175
1176         list_add(&holder->list, &bdev->bd_holder_disks);
1177         goto out_unlock;
1178
1179 out_del:
1180         del_symlink(disk->slave_dir, bdev_kobj(bdev));
1181 out_free:
1182         kfree(holder);
1183 out_unlock:
1184         mutex_unlock(&bdev->bd_mutex);
1185         return ret;
1186 }
1187 EXPORT_SYMBOL_GPL(bd_link_disk_holder);
1188
1189 /**
1190  * bd_unlink_disk_holder - destroy symlinks created by bd_link_disk_holder()
1191  * @bdev: the calimed slave bdev
1192  * @disk: the holding disk
1193  *
1194  * DON'T USE THIS UNLESS YOU'RE ALREADY USING IT.
1195  *
1196  * CONTEXT:
1197  * Might sleep.
1198  */
1199 void bd_unlink_disk_holder(struct block_device *bdev, struct gendisk *disk)
1200 {
1201         struct bd_holder_disk *holder;
1202
1203         mutex_lock(&bdev->bd_mutex);
1204
1205         holder = bd_find_holder_disk(bdev, disk);
1206
1207         if (!WARN_ON_ONCE(holder == NULL) && !--holder->refcnt) {
1208                 del_symlink(disk->slave_dir, bdev_kobj(bdev));
1209                 del_symlink(bdev->bd_part->holder_dir,
1210                             &disk_to_dev(disk)->kobj);
1211                 kobject_put(bdev->bd_part->holder_dir);
1212                 list_del_init(&holder->list);
1213                 kfree(holder);
1214         }
1215
1216         mutex_unlock(&bdev->bd_mutex);
1217 }
1218 EXPORT_SYMBOL_GPL(bd_unlink_disk_holder);
1219 #endif
1220
1221 static void __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part);
1222
1223 int bdev_disk_changed(struct block_device *bdev, bool invalidate)
1224 {
1225         struct gendisk *disk = bdev->bd_disk;
1226         int ret;
1227
1228         lockdep_assert_held(&bdev->bd_mutex);
1229
1230         clear_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1231
1232 rescan:
1233         ret = blk_drop_partitions(bdev);
1234         if (ret)
1235                 return ret;
1236
1237         /*
1238          * Historically we only set the capacity to zero for devices that
1239          * support partitions (independ of actually having partitions created).
1240          * Doing that is rather inconsistent, but changing it broke legacy
1241          * udisks polling for legacy ide-cdrom devices.  Use the crude check
1242          * below to get the sane behavior for most device while not breaking
1243          * userspace for this particular setup.
1244          */
1245         if (invalidate) {
1246                 if (disk_part_scan_enabled(disk) ||
1247                     !(disk->flags & GENHD_FL_REMOVABLE))
1248                         set_capacity(disk, 0);
1249         } else {
1250                 if (disk->fops->revalidate_disk)
1251                         disk->fops->revalidate_disk(disk);
1252         }
1253
1254         if (get_capacity(disk)) {
1255                 ret = blk_add_partitions(disk, bdev);
1256                 if (ret == -EAGAIN)
1257                         goto rescan;
1258         } else if (invalidate) {
1259                 /*
1260                  * Tell userspace that the media / partition table may have
1261                  * changed.
1262                  */
1263                 kobject_uevent(&disk_to_dev(disk)->kobj, KOBJ_CHANGE);
1264         }
1265
1266         return ret;
1267 }
1268 /*
1269  * Only exported for for loop and dasd for historic reasons.  Don't use in new
1270  * code!
1271  */
1272 EXPORT_SYMBOL_GPL(bdev_disk_changed);
1273
1274 /*
1275  * bd_mutex locking:
1276  *
1277  *  mutex_lock(part->bd_mutex)
1278  *    mutex_lock_nested(whole->bd_mutex, 1)
1279  */
1280 static int __blkdev_get(struct block_device *bdev, fmode_t mode)
1281 {
1282         struct gendisk *disk = bdev->bd_disk;
1283         int ret;
1284
1285         if (!bdev->bd_openers) {
1286                 if (!bdev_is_partition(bdev)) {
1287                         ret = -ENXIO;
1288                         bdev->bd_part = disk_get_part(disk, 0);
1289                         if (!bdev->bd_part)
1290                                 goto out_clear;
1291
1292                         ret = 0;
1293                         if (disk->fops->open)
1294                                 ret = disk->fops->open(bdev, mode);
1295
1296                         if (!ret)
1297                                 set_init_blocksize(bdev);
1298
1299                         /*
1300                          * If the device is invalidated, rescan partition
1301                          * if open succeeded or failed with -ENOMEDIUM.
1302                          * The latter is necessary to prevent ghost
1303                          * partitions on a removed medium.
1304                          */
1305                         if (test_bit(GD_NEED_PART_SCAN, &disk->state) &&
1306                             (!ret || ret == -ENOMEDIUM))
1307                                 bdev_disk_changed(bdev, ret == -ENOMEDIUM);
1308
1309                         if (ret)
1310                                 goto out_clear;
1311                 } else {
1312                         struct block_device *whole = bdget_disk(disk, 0);
1313
1314                         mutex_lock_nested(&whole->bd_mutex, 1);
1315                         ret = __blkdev_get(whole, mode);
1316                         if (ret) {
1317                                 mutex_unlock(&whole->bd_mutex);
1318                                 bdput(whole);
1319                                 goto out_clear;
1320                         }
1321                         whole->bd_part_count++;
1322                         mutex_unlock(&whole->bd_mutex);
1323
1324                         bdev->bd_part = disk_get_part(disk, bdev->bd_partno);
1325                         if (!(disk->flags & GENHD_FL_UP) ||
1326                             !bdev->bd_part || !bdev_nr_sectors(bdev)) {
1327                                 __blkdev_put(whole, mode, 1);
1328                                 bdput(whole);
1329                                 ret = -ENXIO;
1330                                 goto out_clear;
1331                         }
1332                         set_init_blocksize(bdev);
1333                 }
1334
1335                 if (bdev->bd_bdi == &noop_backing_dev_info)
1336                         bdev->bd_bdi = bdi_get(disk->queue->backing_dev_info);
1337         } else {
1338                 if (!bdev_is_partition(bdev)) {
1339                         ret = 0;
1340                         if (bdev->bd_disk->fops->open)
1341                                 ret = bdev->bd_disk->fops->open(bdev, mode);
1342                         /* the same as first opener case, read comment there */
1343                         if (test_bit(GD_NEED_PART_SCAN, &disk->state) &&
1344                             (!ret || ret == -ENOMEDIUM))
1345                                 bdev_disk_changed(bdev, ret == -ENOMEDIUM);
1346                         if (ret)
1347                                 return ret;
1348                 }
1349         }
1350         bdev->bd_openers++;
1351         return 0;
1352
1353  out_clear:
1354         disk_put_part(bdev->bd_part);
1355         bdev->bd_part = NULL;
1356         return ret;
1357 }
1358
1359 struct block_device *blkdev_get_no_open(dev_t dev)
1360 {
1361         struct block_device *bdev;
1362         struct gendisk *disk;
1363
1364         down_read(&bdev_lookup_sem);
1365         bdev = bdget(dev);
1366         if (!bdev) {
1367                 up_read(&bdev_lookup_sem);
1368                 blk_request_module(dev);
1369                 down_read(&bdev_lookup_sem);
1370
1371                 bdev = bdget(dev);
1372                 if (!bdev)
1373                         goto unlock;
1374         }
1375
1376         disk = bdev->bd_disk;
1377         if (!kobject_get_unless_zero(&disk_to_dev(disk)->kobj))
1378                 goto bdput;
1379         if ((disk->flags & (GENHD_FL_UP | GENHD_FL_HIDDEN)) != GENHD_FL_UP)
1380                 goto put_disk;
1381         if (!try_module_get(bdev->bd_disk->fops->owner))
1382                 goto put_disk;
1383         up_read(&bdev_lookup_sem);
1384         return bdev;
1385 put_disk:
1386         put_disk(disk);
1387 bdput:
1388         bdput(bdev);
1389 unlock:
1390         up_read(&bdev_lookup_sem);
1391         return NULL;
1392 }
1393
1394 void blkdev_put_no_open(struct block_device *bdev)
1395 {
1396         module_put(bdev->bd_disk->fops->owner);
1397         put_disk(bdev->bd_disk);
1398         bdput(bdev);
1399 }
1400
1401 /**
1402  * blkdev_get_by_dev - open a block device by device number
1403  * @dev: device number of block device to open
1404  * @mode: FMODE_* mask
1405  * @holder: exclusive holder identifier
1406  *
1407  * Open the block device described by device number @dev. If @mode includes
1408  * %FMODE_EXCL, the block device is opened with exclusive access.  Specifying
1409  * %FMODE_EXCL with a %NULL @holder is invalid.  Exclusive opens may nest for
1410  * the same @holder.
1411  *
1412  * Use this interface ONLY if you really do not have anything better - i.e. when
1413  * you are behind a truly sucky interface and all you are given is a device
1414  * number.  Everything else should use blkdev_get_by_path().
1415  *
1416  * CONTEXT:
1417  * Might sleep.
1418  *
1419  * RETURNS:
1420  * Reference to the block_device on success, ERR_PTR(-errno) on failure.
1421  */
1422 struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode, void *holder)
1423 {
1424         bool unblock_events = true;
1425         struct block_device *bdev;
1426         struct gendisk *disk;
1427         int ret;
1428
1429         ret = devcgroup_check_permission(DEVCG_DEV_BLOCK,
1430                         MAJOR(dev), MINOR(dev),
1431                         ((mode & FMODE_READ) ? DEVCG_ACC_READ : 0) |
1432                         ((mode & FMODE_WRITE) ? DEVCG_ACC_WRITE : 0));
1433         if (ret)
1434                 return ERR_PTR(ret);
1435
1436         /*
1437          * If we lost a race with 'disk' being deleted, try again.  See md.c.
1438          */
1439 retry:
1440         bdev = blkdev_get_no_open(dev);
1441         if (!bdev)
1442                 return ERR_PTR(-ENXIO);
1443         disk = bdev->bd_disk;
1444
1445         if (mode & FMODE_EXCL) {
1446                 ret = bd_prepare_to_claim(bdev, holder);
1447                 if (ret)
1448                         goto put_blkdev;
1449         }
1450
1451         disk_block_events(disk);
1452
1453         mutex_lock(&bdev->bd_mutex);
1454         ret =__blkdev_get(bdev, mode);
1455         if (ret)
1456                 goto abort_claiming;
1457         if (mode & FMODE_EXCL) {
1458                 bd_finish_claiming(bdev, holder);
1459
1460                 /*
1461                  * Block event polling for write claims if requested.  Any write
1462                  * holder makes the write_holder state stick until all are
1463                  * released.  This is good enough and tracking individual
1464                  * writeable reference is too fragile given the way @mode is
1465                  * used in blkdev_get/put().
1466                  */
1467                 if ((mode & FMODE_WRITE) && !bdev->bd_write_holder &&
1468                     (disk->flags & GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE)) {
1469                         bdev->bd_write_holder = true;
1470                         unblock_events = false;
1471                 }
1472         }
1473         mutex_unlock(&bdev->bd_mutex);
1474
1475         if (unblock_events)
1476                 disk_unblock_events(disk);
1477         return bdev;
1478
1479 abort_claiming:
1480         if (mode & FMODE_EXCL)
1481                 bd_abort_claiming(bdev, holder);
1482         mutex_unlock(&bdev->bd_mutex);
1483         disk_unblock_events(disk);
1484 put_blkdev:
1485         blkdev_put_no_open(bdev);
1486         if (ret == -ERESTARTSYS)
1487                 goto retry;
1488         return ERR_PTR(ret);
1489 }
1490 EXPORT_SYMBOL(blkdev_get_by_dev);
1491
1492 /**
1493  * blkdev_get_by_path - open a block device by name
1494  * @path: path to the block device to open
1495  * @mode: FMODE_* mask
1496  * @holder: exclusive holder identifier
1497  *
1498  * Open the block device described by the device file at @path.  If @mode
1499  * includes %FMODE_EXCL, the block device is opened with exclusive access.
1500  * Specifying %FMODE_EXCL with a %NULL @holder is invalid.  Exclusive opens may
1501  * nest for the same @holder.
1502  *
1503  * CONTEXT:
1504  * Might sleep.
1505  *
1506  * RETURNS:
1507  * Reference to the block_device on success, ERR_PTR(-errno) on failure.
1508  */
1509 struct block_device *blkdev_get_by_path(const char *path, fmode_t mode,
1510                                         void *holder)
1511 {
1512         struct block_device *bdev;
1513         dev_t dev;
1514         int error;
1515
1516         error = lookup_bdev(path, &dev);
1517         if (error)
1518                 return ERR_PTR(error);
1519
1520         bdev = blkdev_get_by_dev(dev, mode, holder);
1521         if (!IS_ERR(bdev) && (mode & FMODE_WRITE) && bdev_read_only(bdev)) {
1522                 blkdev_put(bdev, mode);
1523                 return ERR_PTR(-EACCES);
1524         }
1525
1526         return bdev;
1527 }
1528 EXPORT_SYMBOL(blkdev_get_by_path);
1529
1530 static int blkdev_open(struct inode * inode, struct file * filp)
1531 {
1532         struct block_device *bdev;
1533
1534         /*
1535          * Preserve backwards compatibility and allow large file access
1536          * even if userspace doesn't ask for it explicitly. Some mkfs
1537          * binary needs it. We might want to drop this workaround
1538          * during an unstable branch.
1539          */
1540         filp->f_flags |= O_LARGEFILE;
1541
1542         filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC;
1543
1544         if (filp->f_flags & O_NDELAY)
1545                 filp->f_mode |= FMODE_NDELAY;
1546         if (filp->f_flags & O_EXCL)
1547                 filp->f_mode |= FMODE_EXCL;
1548         if ((filp->f_flags & O_ACCMODE) == 3)
1549                 filp->f_mode |= FMODE_WRITE_IOCTL;
1550
1551         bdev = blkdev_get_by_dev(inode->i_rdev, filp->f_mode, filp);
1552         if (IS_ERR(bdev))
1553                 return PTR_ERR(bdev);
1554         filp->f_mapping = bdev->bd_inode->i_mapping;
1555         filp->f_wb_err = filemap_sample_wb_err(filp->f_mapping);
1556         return 0;
1557 }
1558
1559 static void __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part)
1560 {
1561         struct gendisk *disk = bdev->bd_disk;
1562         struct block_device *victim = NULL;
1563
1564         /*
1565          * Sync early if it looks like we're the last one.  If someone else
1566          * opens the block device between now and the decrement of bd_openers
1567          * then we did a sync that we didn't need to, but that's not the end
1568          * of the world and we want to avoid long (could be several minute)
1569          * syncs while holding the mutex.
1570          */
1571         if (bdev->bd_openers == 1)
1572                 sync_blockdev(bdev);
1573
1574         mutex_lock_nested(&bdev->bd_mutex, for_part);
1575         if (for_part)
1576                 bdev->bd_part_count--;
1577
1578         if (!--bdev->bd_openers) {
1579                 WARN_ON_ONCE(bdev->bd_holders);
1580                 sync_blockdev(bdev);
1581                 kill_bdev(bdev);
1582                 bdev_write_inode(bdev);
1583
1584                 if (!bdev_is_partition(bdev) && disk->fops->release)
1585                         disk->fops->release(disk, mode);
1586
1587                 disk_put_part(bdev->bd_part);
1588                 bdev->bd_part = NULL;
1589                 if (bdev_is_partition(bdev))
1590                         victim = bdev_whole(bdev);
1591         } else {
1592                 if (!bdev_is_partition(bdev) && disk->fops->release)
1593                         disk->fops->release(disk, mode);
1594         }
1595         mutex_unlock(&bdev->bd_mutex);
1596         if (victim) {
1597                 __blkdev_put(victim, mode, 1);
1598                 bdput(victim);
1599         }
1600 }
1601
1602 void blkdev_put(struct block_device *bdev, fmode_t mode)
1603 {
1604         struct gendisk *disk = bdev->bd_disk;
1605
1606         mutex_lock(&bdev->bd_mutex);
1607
1608         if (mode & FMODE_EXCL) {
1609                 struct block_device *whole = bdev_whole(bdev);
1610                 bool bdev_free;
1611
1612                 /*
1613                  * Release a claim on the device.  The holder fields
1614                  * are protected with bdev_lock.  bd_mutex is to
1615                  * synchronize disk_holder unlinking.
1616                  */
1617                 spin_lock(&bdev_lock);
1618
1619                 WARN_ON_ONCE(--bdev->bd_holders < 0);
1620                 WARN_ON_ONCE(--whole->bd_holders < 0);
1621
1622                 if ((bdev_free = !bdev->bd_holders))
1623                         bdev->bd_holder = NULL;
1624                 if (!whole->bd_holders)
1625                         whole->bd_holder = NULL;
1626
1627                 spin_unlock(&bdev_lock);
1628
1629                 /*
1630                  * If this was the last claim, remove holder link and
1631                  * unblock evpoll if it was a write holder.
1632                  */
1633                 if (bdev_free && bdev->bd_write_holder) {
1634                         disk_unblock_events(disk);
1635                         bdev->bd_write_holder = false;
1636                 }
1637         }
1638
1639         /*
1640          * Trigger event checking and tell drivers to flush MEDIA_CHANGE
1641          * event.  This is to ensure detection of media removal commanded
1642          * from userland - e.g. eject(1).
1643          */
1644         disk_flush_events(disk, DISK_EVENT_MEDIA_CHANGE);
1645         mutex_unlock(&bdev->bd_mutex);
1646
1647         __blkdev_put(bdev, mode, 0);
1648         blkdev_put_no_open(bdev);
1649 }
1650 EXPORT_SYMBOL(blkdev_put);
1651
1652 static int blkdev_close(struct inode * inode, struct file * filp)
1653 {
1654         struct block_device *bdev = I_BDEV(bdev_file_inode(filp));
1655         blkdev_put(bdev, filp->f_mode);
1656         return 0;
1657 }
1658
1659 static long block_ioctl(struct file *file, unsigned cmd, unsigned long arg)
1660 {
1661         struct block_device *bdev = I_BDEV(bdev_file_inode(file));
1662         fmode_t mode = file->f_mode;
1663
1664         /*
1665          * O_NDELAY can be altered using fcntl(.., F_SETFL, ..), so we have
1666          * to updated it before every ioctl.
1667          */
1668         if (file->f_flags & O_NDELAY)
1669                 mode |= FMODE_NDELAY;
1670         else
1671                 mode &= ~FMODE_NDELAY;
1672
1673         return blkdev_ioctl(bdev, mode, cmd, arg);
1674 }
1675
1676 /*
1677  * Write data to the block device.  Only intended for the block device itself
1678  * and the raw driver which basically is a fake block device.
1679  *
1680  * Does not take i_mutex for the write and thus is not for general purpose
1681  * use.
1682  */
1683 ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
1684 {
1685         struct file *file = iocb->ki_filp;
1686         struct inode *bd_inode = bdev_file_inode(file);
1687         loff_t size = i_size_read(bd_inode);
1688         struct blk_plug plug;
1689         ssize_t ret;
1690
1691         if (bdev_read_only(I_BDEV(bd_inode)))
1692                 return -EPERM;
1693
1694         if (IS_SWAPFILE(bd_inode) && !is_hibernate_resume_dev(bd_inode->i_rdev))
1695                 return -ETXTBSY;
1696
1697         if (!iov_iter_count(from))
1698                 return 0;
1699
1700         if (iocb->ki_pos >= size)
1701                 return -ENOSPC;
1702
1703         if ((iocb->ki_flags & (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT)
1704                 return -EOPNOTSUPP;
1705
1706         iov_iter_truncate(from, size - iocb->ki_pos);
1707
1708         blk_start_plug(&plug);
1709         ret = __generic_file_write_iter(iocb, from);
1710         if (ret > 0)
1711                 ret = generic_write_sync(iocb, ret);
1712         blk_finish_plug(&plug);
1713         return ret;
1714 }
1715 EXPORT_SYMBOL_GPL(blkdev_write_iter);
1716
1717 ssize_t blkdev_read_iter(struct kiocb *iocb, struct iov_iter *to)
1718 {
1719         struct file *file = iocb->ki_filp;
1720         struct inode *bd_inode = bdev_file_inode(file);
1721         loff_t size = i_size_read(bd_inode);
1722         loff_t pos = iocb->ki_pos;
1723
1724         if (pos >= size)
1725                 return 0;
1726
1727         size -= pos;
1728         iov_iter_truncate(to, size);
1729         return generic_file_read_iter(iocb, to);
1730 }
1731 EXPORT_SYMBOL_GPL(blkdev_read_iter);
1732
1733 /*
1734  * Try to release a page associated with block device when the system
1735  * is under memory pressure.
1736  */
1737 static int blkdev_releasepage(struct page *page, gfp_t wait)
1738 {
1739         struct super_block *super = BDEV_I(page->mapping->host)->bdev.bd_super;
1740
1741         if (super && super->s_op->bdev_try_to_free_page)
1742                 return super->s_op->bdev_try_to_free_page(super, page, wait);
1743
1744         return try_to_free_buffers(page);
1745 }
1746
1747 static int blkdev_writepages(struct address_space *mapping,
1748                              struct writeback_control *wbc)
1749 {
1750         return generic_writepages(mapping, wbc);
1751 }
1752
1753 static const struct address_space_operations def_blk_aops = {
1754         .readpage       = blkdev_readpage,
1755         .readahead      = blkdev_readahead,
1756         .writepage      = blkdev_writepage,
1757         .write_begin    = blkdev_write_begin,
1758         .write_end      = blkdev_write_end,
1759         .writepages     = blkdev_writepages,
1760         .releasepage    = blkdev_releasepage,
1761         .direct_IO      = blkdev_direct_IO,
1762         .migratepage    = buffer_migrate_page_norefs,
1763         .is_dirty_writeback = buffer_check_dirty_writeback,
1764 };
1765
1766 #define BLKDEV_FALLOC_FL_SUPPORTED                                      \
1767                 (FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |           \
1768                  FALLOC_FL_ZERO_RANGE | FALLOC_FL_NO_HIDE_STALE)
1769
1770 static long blkdev_fallocate(struct file *file, int mode, loff_t start,
1771                              loff_t len)
1772 {
1773         struct block_device *bdev = I_BDEV(bdev_file_inode(file));
1774         loff_t end = start + len - 1;
1775         loff_t isize;
1776         int error;
1777
1778         /* Fail if we don't recognize the flags. */
1779         if (mode & ~BLKDEV_FALLOC_FL_SUPPORTED)
1780                 return -EOPNOTSUPP;
1781
1782         /* Don't go off the end of the device. */
1783         isize = i_size_read(bdev->bd_inode);
1784         if (start >= isize)
1785                 return -EINVAL;
1786         if (end >= isize) {
1787                 if (mode & FALLOC_FL_KEEP_SIZE) {
1788                         len = isize - start;
1789                         end = start + len - 1;
1790                 } else
1791                         return -EINVAL;
1792         }
1793
1794         /*
1795          * Don't allow IO that isn't aligned to logical block size.
1796          */
1797         if ((start | len) & (bdev_logical_block_size(bdev) - 1))
1798                 return -EINVAL;
1799
1800         /* Invalidate the page cache, including dirty pages. */
1801         error = truncate_bdev_range(bdev, file->f_mode, start, end);
1802         if (error)
1803                 return error;
1804
1805         switch (mode) {
1806         case FALLOC_FL_ZERO_RANGE:
1807         case FALLOC_FL_ZERO_RANGE | FALLOC_FL_KEEP_SIZE:
1808                 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
1809                                             GFP_KERNEL, BLKDEV_ZERO_NOUNMAP);
1810                 break;
1811         case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE:
1812                 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
1813                                              GFP_KERNEL, BLKDEV_ZERO_NOFALLBACK);
1814                 break;
1815         case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE | FALLOC_FL_NO_HIDE_STALE:
1816                 error = blkdev_issue_discard(bdev, start >> 9, len >> 9,
1817                                              GFP_KERNEL, 0);
1818                 break;
1819         default:
1820                 return -EOPNOTSUPP;
1821         }
1822         if (error)
1823                 return error;
1824
1825         /*
1826          * Invalidate again; if someone wandered in and dirtied a page,
1827          * the caller will be given -EBUSY.  The third argument is
1828          * inclusive, so the rounding here is safe.
1829          */
1830         return invalidate_inode_pages2_range(bdev->bd_inode->i_mapping,
1831                                              start >> PAGE_SHIFT,
1832                                              end >> PAGE_SHIFT);
1833 }
1834
1835 const struct file_operations def_blk_fops = {
1836         .open           = blkdev_open,
1837         .release        = blkdev_close,
1838         .llseek         = block_llseek,
1839         .read_iter      = blkdev_read_iter,
1840         .write_iter     = blkdev_write_iter,
1841         .iopoll         = blkdev_iopoll,
1842         .mmap           = generic_file_mmap,
1843         .fsync          = blkdev_fsync,
1844         .unlocked_ioctl = block_ioctl,
1845 #ifdef CONFIG_COMPAT
1846         .compat_ioctl   = compat_blkdev_ioctl,
1847 #endif
1848         .splice_read    = generic_file_splice_read,
1849         .splice_write   = iter_file_splice_write,
1850         .fallocate      = blkdev_fallocate,
1851 };
1852
1853 /**
1854  * lookup_bdev  - lookup a struct block_device by name
1855  * @pathname:   special file representing the block device
1856  *
1857  * Get a reference to the blockdevice at @pathname in the current
1858  * namespace if possible and return it.  Return ERR_PTR(error)
1859  * otherwise.
1860  */
1861 int lookup_bdev(const char *pathname, dev_t *dev)
1862 {
1863         struct inode *inode;
1864         struct path path;
1865         int error;
1866
1867         if (!pathname || !*pathname)
1868                 return -EINVAL;
1869
1870         error = kern_path(pathname, LOOKUP_FOLLOW, &path);
1871         if (error)
1872                 return error;
1873
1874         inode = d_backing_inode(path.dentry);
1875         error = -ENOTBLK;
1876         if (!S_ISBLK(inode->i_mode))
1877                 goto out_path_put;
1878         error = -EACCES;
1879         if (!may_open_dev(&path))
1880                 goto out_path_put;
1881
1882         *dev = inode->i_rdev;
1883         error = 0;
1884 out_path_put:
1885         path_put(&path);
1886         return error;
1887 }
1888 EXPORT_SYMBOL(lookup_bdev);
1889
1890 int __invalidate_device(struct block_device *bdev, bool kill_dirty)
1891 {
1892         struct super_block *sb = get_super(bdev);
1893         int res = 0;
1894
1895         if (sb) {
1896                 /*
1897                  * no need to lock the super, get_super holds the
1898                  * read mutex so the filesystem cannot go away
1899                  * under us (->put_super runs with the write lock
1900                  * hold).
1901                  */
1902                 shrink_dcache_sb(sb);
1903                 res = invalidate_inodes(sb, kill_dirty);
1904                 drop_super(sb);
1905         }
1906         invalidate_bdev(bdev);
1907         return res;
1908 }
1909 EXPORT_SYMBOL(__invalidate_device);
1910
1911 void iterate_bdevs(void (*func)(struct block_device *, void *), void *arg)
1912 {
1913         struct inode *inode, *old_inode = NULL;
1914
1915         spin_lock(&blockdev_superblock->s_inode_list_lock);
1916         list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list) {
1917                 struct address_space *mapping = inode->i_mapping;
1918                 struct block_device *bdev;
1919
1920                 spin_lock(&inode->i_lock);
1921                 if (inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW) ||
1922                     mapping->nrpages == 0) {
1923                         spin_unlock(&inode->i_lock);
1924                         continue;
1925                 }
1926                 __iget(inode);
1927                 spin_unlock(&inode->i_lock);
1928                 spin_unlock(&blockdev_superblock->s_inode_list_lock);
1929                 /*
1930                  * We hold a reference to 'inode' so it couldn't have been
1931                  * removed from s_inodes list while we dropped the
1932                  * s_inode_list_lock  We cannot iput the inode now as we can
1933                  * be holding the last reference and we cannot iput it under
1934                  * s_inode_list_lock. So we keep the reference and iput it
1935                  * later.
1936                  */
1937                 iput(old_inode);
1938                 old_inode = inode;
1939                 bdev = I_BDEV(inode);
1940
1941                 mutex_lock(&bdev->bd_mutex);
1942                 if (bdev->bd_openers)
1943                         func(bdev, arg);
1944                 mutex_unlock(&bdev->bd_mutex);
1945
1946                 spin_lock(&blockdev_superblock->s_inode_list_lock);
1947         }
1948         spin_unlock(&blockdev_superblock->s_inode_list_lock);
1949         iput(old_inode);
1950 }