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