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