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