OSDN Git Service

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