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