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