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