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