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