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