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