Merge branch 'stable-3.2' into pandora-3.2
[pandora-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/module.h>
18 #include <linux/blkpg.h>
19 #include <linux/buffer_head.h>
20 #include <linux/pagevec.h>
21 #include <linux/writeback.h>
22 #include <linux/mpage.h>
23 #include <linux/mount.h>
24 #include <linux/uio.h>
25 #include <linux/namei.h>
26 #include <linux/log2.h>
27 #include <linux/kmemleak.h>
28 #include <asm/uaccess.h>
29 #include "internal.h"
30
31 struct bdev_inode {
32         struct block_device bdev;
33         struct inode vfs_inode;
34 };
35
36 static const struct address_space_operations def_blk_aops;
37
38 static inline struct bdev_inode *BDEV_I(struct inode *inode)
39 {
40         return container_of(inode, struct bdev_inode, vfs_inode);
41 }
42
43 inline struct block_device *I_BDEV(struct inode *inode)
44 {
45         return &BDEV_I(inode)->bdev;
46 }
47 EXPORT_SYMBOL(I_BDEV);
48
49 /*
50  * Move the inode from its current bdi to a new bdi. If the inode is dirty we
51  * need to move it onto the dirty list of @dst so that the inode is always on
52  * the right list.
53  */
54 static void bdev_inode_switch_bdi(struct inode *inode,
55                         struct backing_dev_info *dst)
56 {
57         struct backing_dev_info *old = inode->i_data.backing_dev_info;
58
59         if (unlikely(dst == old))               /* deadlock avoidance */
60                 return;
61         bdi_lock_two(&old->wb, &dst->wb);
62         spin_lock(&inode->i_lock);
63         inode->i_data.backing_dev_info = dst;
64         if (inode->i_state & I_DIRTY)
65                 list_move(&inode->i_wb_list, &dst->wb.b_dirty);
66         spin_unlock(&inode->i_lock);
67         spin_unlock(&old->wb.list_lock);
68         spin_unlock(&dst->wb.list_lock);
69 }
70
71 sector_t blkdev_max_block(struct block_device *bdev)
72 {
73         sector_t retval = ~((sector_t)0);
74         loff_t sz = i_size_read(bdev->bd_inode);
75
76         if (sz) {
77                 unsigned int size = block_size(bdev);
78                 unsigned int sizebits = blksize_bits(size);
79                 retval = (sz >> sizebits);
80         }
81         return retval;
82 }
83
84 /* Kill _all_ buffers and pagecache , dirty or not.. */
85 void kill_bdev(struct block_device *bdev)
86 {
87         if (bdev->bd_inode->i_mapping->nrpages == 0)
88                 return;
89         invalidate_bh_lrus();
90         truncate_inode_pages(bdev->bd_inode->i_mapping, 0);
91 }       
92 EXPORT_SYMBOL(kill_bdev);
93
94 int set_blocksize(struct block_device *bdev, int size)
95 {
96         /* Size must be a power of two, and between 512 and PAGE_SIZE */
97         if (size > PAGE_SIZE || size < 512 || !is_power_of_2(size))
98                 return -EINVAL;
99
100         /* Size cannot be smaller than the size supported by the device */
101         if (size < bdev_logical_block_size(bdev))
102                 return -EINVAL;
103
104         /* Don't change the size if it is same as current */
105         if (bdev->bd_block_size != size) {
106                 sync_blockdev(bdev);
107                 bdev->bd_block_size = size;
108                 bdev->bd_inode->i_blkbits = blksize_bits(size);
109                 kill_bdev(bdev);
110         }
111         return 0;
112 }
113
114 EXPORT_SYMBOL(set_blocksize);
115
116 int sb_set_blocksize(struct super_block *sb, int size)
117 {
118         if (set_blocksize(sb->s_bdev, size))
119                 return 0;
120         /* If we get here, we know size is power of two
121          * and it's value is between 512 and PAGE_SIZE */
122         sb->s_blocksize = size;
123         sb->s_blocksize_bits = blksize_bits(size);
124         return sb->s_blocksize;
125 }
126
127 EXPORT_SYMBOL(sb_set_blocksize);
128
129 int sb_min_blocksize(struct super_block *sb, int size)
130 {
131         int minsize = bdev_logical_block_size(sb->s_bdev);
132         if (size < minsize)
133                 size = minsize;
134         return sb_set_blocksize(sb, size);
135 }
136
137 EXPORT_SYMBOL(sb_min_blocksize);
138
139 static int
140 blkdev_get_block(struct inode *inode, sector_t iblock,
141                 struct buffer_head *bh, int create)
142 {
143         if (iblock >= blkdev_max_block(I_BDEV(inode))) {
144                 if (create)
145                         return -EIO;
146
147                 /*
148                  * for reads, we're just trying to fill a partial page.
149                  * return a hole, they will have to call get_block again
150                  * before they can fill it, and they will get -EIO at that
151                  * time
152                  */
153                 return 0;
154         }
155         bh->b_bdev = I_BDEV(inode);
156         bh->b_blocknr = iblock;
157         set_buffer_mapped(bh);
158         return 0;
159 }
160
161 static int
162 blkdev_get_blocks(struct inode *inode, sector_t iblock,
163                 struct buffer_head *bh, int create)
164 {
165         sector_t end_block = blkdev_max_block(I_BDEV(inode));
166         unsigned long max_blocks = bh->b_size >> inode->i_blkbits;
167
168         if ((iblock + max_blocks) > end_block) {
169                 max_blocks = end_block - iblock;
170                 if ((long)max_blocks <= 0) {
171                         if (create)
172                                 return -EIO;    /* write fully beyond EOF */
173                         /*
174                          * It is a read which is fully beyond EOF.  We return
175                          * a !buffer_mapped buffer
176                          */
177                         max_blocks = 0;
178                 }
179         }
180
181         bh->b_bdev = I_BDEV(inode);
182         bh->b_blocknr = iblock;
183         bh->b_size = max_blocks << inode->i_blkbits;
184         if (max_blocks)
185                 set_buffer_mapped(bh);
186         return 0;
187 }
188
189 static ssize_t
190 blkdev_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
191                         loff_t offset, unsigned long nr_segs)
192 {
193         struct file *file = iocb->ki_filp;
194         struct inode *inode = file->f_mapping->host;
195
196         return __blockdev_direct_IO(rw, iocb, inode, I_BDEV(inode), iov, offset,
197                                     nr_segs, blkdev_get_blocks, NULL, NULL, 0);
198 }
199
200 int __sync_blockdev(struct block_device *bdev, int wait)
201 {
202         if (!bdev)
203                 return 0;
204         if (!wait)
205                 return filemap_flush(bdev->bd_inode->i_mapping);
206         return filemap_write_and_wait(bdev->bd_inode->i_mapping);
207 }
208
209 /*
210  * Write out and wait upon all the dirty data associated with a block
211  * device via its mapping.  Does not take the superblock lock.
212  */
213 int sync_blockdev(struct block_device *bdev)
214 {
215         return __sync_blockdev(bdev, 1);
216 }
217 EXPORT_SYMBOL(sync_blockdev);
218
219 /*
220  * Write out and wait upon all dirty data associated with this
221  * device.   Filesystem data as well as the underlying block
222  * device.  Takes the superblock lock.
223  */
224 int fsync_bdev(struct block_device *bdev)
225 {
226         struct super_block *sb = get_super(bdev);
227         if (sb) {
228                 int res = sync_filesystem(sb);
229                 drop_super(sb);
230                 return res;
231         }
232         return sync_blockdev(bdev);
233 }
234 EXPORT_SYMBOL(fsync_bdev);
235
236 /**
237  * freeze_bdev  --  lock a filesystem and force it into a consistent state
238  * @bdev:       blockdevice to lock
239  *
240  * If a superblock is found on this device, we take the s_umount semaphore
241  * on it to make sure nobody unmounts until the snapshot creation is done.
242  * The reference counter (bd_fsfreeze_count) guarantees that only the last
243  * unfreeze process can unfreeze the frozen filesystem actually when multiple
244  * freeze requests arrive simultaneously. It counts up in freeze_bdev() and
245  * count down in thaw_bdev(). When it becomes 0, thaw_bdev() will unfreeze
246  * actually.
247  */
248 struct super_block *freeze_bdev(struct block_device *bdev)
249 {
250         struct super_block *sb;
251         int error = 0;
252
253         mutex_lock(&bdev->bd_fsfreeze_mutex);
254         if (++bdev->bd_fsfreeze_count > 1) {
255                 /*
256                  * We don't even need to grab a reference - the first call
257                  * to freeze_bdev grab an active reference and only the last
258                  * thaw_bdev drops it.
259                  */
260                 sb = get_super(bdev);
261                 drop_super(sb);
262                 mutex_unlock(&bdev->bd_fsfreeze_mutex);
263                 return sb;
264         }
265
266         sb = get_active_super(bdev);
267         if (!sb)
268                 goto out;
269         error = freeze_super(sb);
270         if (error) {
271                 deactivate_super(sb);
272                 bdev->bd_fsfreeze_count--;
273                 mutex_unlock(&bdev->bd_fsfreeze_mutex);
274                 return ERR_PTR(error);
275         }
276         deactivate_super(sb);
277  out:
278         sync_blockdev(bdev);
279         mutex_unlock(&bdev->bd_fsfreeze_mutex);
280         return sb;      /* thaw_bdev releases s->s_umount */
281 }
282 EXPORT_SYMBOL(freeze_bdev);
283
284 /**
285  * thaw_bdev  -- unlock filesystem
286  * @bdev:       blockdevice to unlock
287  * @sb:         associated superblock
288  *
289  * Unlocks the filesystem and marks it writeable again after freeze_bdev().
290  */
291 int thaw_bdev(struct block_device *bdev, struct super_block *sb)
292 {
293         int error = -EINVAL;
294
295         mutex_lock(&bdev->bd_fsfreeze_mutex);
296         if (!bdev->bd_fsfreeze_count)
297                 goto out;
298
299         error = 0;
300         if (--bdev->bd_fsfreeze_count > 0)
301                 goto out;
302
303         if (!sb)
304                 goto out;
305
306         error = thaw_super(sb);
307         if (error) {
308                 bdev->bd_fsfreeze_count++;
309                 mutex_unlock(&bdev->bd_fsfreeze_mutex);
310                 return error;
311         }
312 out:
313         mutex_unlock(&bdev->bd_fsfreeze_mutex);
314         return 0;
315 }
316 EXPORT_SYMBOL(thaw_bdev);
317
318 static int blkdev_writepage(struct page *page, struct writeback_control *wbc)
319 {
320         return block_write_full_page(page, blkdev_get_block, wbc);
321 }
322
323 static int blkdev_readpage(struct file * file, struct page * page)
324 {
325         return block_read_full_page(page, blkdev_get_block);
326 }
327
328 static int blkdev_write_begin(struct file *file, struct address_space *mapping,
329                         loff_t pos, unsigned len, unsigned flags,
330                         struct page **pagep, void **fsdata)
331 {
332         return block_write_begin(mapping, pos, len, flags, pagep,
333                                  blkdev_get_block);
334 }
335
336 static int blkdev_write_end(struct file *file, struct address_space *mapping,
337                         loff_t pos, unsigned len, unsigned copied,
338                         struct page *page, void *fsdata)
339 {
340         int ret;
341         ret = block_write_end(file, mapping, pos, len, copied, page, fsdata);
342
343         unlock_page(page);
344         page_cache_release(page);
345
346         return ret;
347 }
348
349 /*
350  * private llseek:
351  * for a block special file file->f_path.dentry->d_inode->i_size is zero
352  * so we compute the size by hand (just as in block_read/write above)
353  */
354 static loff_t block_llseek(struct file *file, loff_t offset, int origin)
355 {
356         struct inode *bd_inode = file->f_mapping->host;
357         loff_t size;
358         loff_t retval;
359
360         mutex_lock(&bd_inode->i_mutex);
361         size = i_size_read(bd_inode);
362
363         retval = -EINVAL;
364         switch (origin) {
365                 case SEEK_END:
366                         offset += size;
367                         break;
368                 case SEEK_CUR:
369                         offset += file->f_pos;
370                 case SEEK_SET:
371                         break;
372                 default:
373                         goto out;
374         }
375         if (offset >= 0 && offset <= size) {
376                 if (offset != file->f_pos) {
377                         file->f_pos = offset;
378                 }
379                 retval = offset;
380         }
381 out:
382         mutex_unlock(&bd_inode->i_mutex);
383         return retval;
384 }
385         
386 int blkdev_fsync(struct file *filp, loff_t start, loff_t end, int datasync)
387 {
388         struct inode *bd_inode = filp->f_mapping->host;
389         struct block_device *bdev = I_BDEV(bd_inode);
390         int error;
391         
392         error = filemap_write_and_wait_range(filp->f_mapping, start, end);
393         if (error)
394                 return error;
395
396         /*
397          * There is no need to serialise calls to blkdev_issue_flush with
398          * i_mutex and doing so causes performance issues with concurrent
399          * O_SYNC writers to a block device.
400          */
401         error = blkdev_issue_flush(bdev, GFP_KERNEL, NULL);
402         if (error == -EOPNOTSUPP)
403                 error = 0;
404
405         return error;
406 }
407 EXPORT_SYMBOL(blkdev_fsync);
408
409 /*
410  * pseudo-fs
411  */
412
413 static  __cacheline_aligned_in_smp DEFINE_SPINLOCK(bdev_lock);
414 static struct kmem_cache * bdev_cachep __read_mostly;
415
416 static struct inode *bdev_alloc_inode(struct super_block *sb)
417 {
418         struct bdev_inode *ei = kmem_cache_alloc(bdev_cachep, GFP_KERNEL);
419         if (!ei)
420                 return NULL;
421         return &ei->vfs_inode;
422 }
423
424 static void bdev_i_callback(struct rcu_head *head)
425 {
426         struct inode *inode = container_of(head, struct inode, i_rcu);
427         struct bdev_inode *bdi = BDEV_I(inode);
428
429         INIT_LIST_HEAD(&inode->i_dentry);
430         kmem_cache_free(bdev_cachep, bdi);
431 }
432
433 static void bdev_destroy_inode(struct inode *inode)
434 {
435         call_rcu(&inode->i_rcu, bdev_i_callback);
436 }
437
438 static void init_once(void *foo)
439 {
440         struct bdev_inode *ei = (struct bdev_inode *) foo;
441         struct block_device *bdev = &ei->bdev;
442
443         memset(bdev, 0, sizeof(*bdev));
444         mutex_init(&bdev->bd_mutex);
445         INIT_LIST_HEAD(&bdev->bd_inodes);
446         INIT_LIST_HEAD(&bdev->bd_list);
447 #ifdef CONFIG_SYSFS
448         INIT_LIST_HEAD(&bdev->bd_holder_disks);
449 #endif
450         inode_init_once(&ei->vfs_inode);
451         /* Initialize mutex for freeze. */
452         mutex_init(&bdev->bd_fsfreeze_mutex);
453 }
454
455 static inline void __bd_forget(struct inode *inode)
456 {
457         list_del_init(&inode->i_devices);
458         inode->i_bdev = NULL;
459         inode->i_mapping = &inode->i_data;
460 }
461
462 static void bdev_evict_inode(struct inode *inode)
463 {
464         struct block_device *bdev = &BDEV_I(inode)->bdev;
465         struct list_head *p;
466         truncate_inode_pages(&inode->i_data, 0);
467         invalidate_inode_buffers(inode); /* is it needed here? */
468         end_writeback(inode);
469         spin_lock(&bdev_lock);
470         while ( (p = bdev->bd_inodes.next) != &bdev->bd_inodes ) {
471                 __bd_forget(list_entry(p, struct inode, i_devices));
472         }
473         list_del_init(&bdev->bd_list);
474         spin_unlock(&bdev_lock);
475 }
476
477 static const struct super_operations bdev_sops = {
478         .statfs = simple_statfs,
479         .alloc_inode = bdev_alloc_inode,
480         .destroy_inode = bdev_destroy_inode,
481         .drop_inode = generic_delete_inode,
482         .evict_inode = bdev_evict_inode,
483 };
484
485 static struct dentry *bd_mount(struct file_system_type *fs_type,
486         int flags, const char *dev_name, void *data)
487 {
488         return mount_pseudo(fs_type, "bdev:", &bdev_sops, NULL, 0x62646576);
489 }
490
491 static struct file_system_type bd_type = {
492         .name           = "bdev",
493         .mount          = bd_mount,
494         .kill_sb        = kill_anon_super,
495 };
496
497 struct super_block *blockdev_superblock __read_mostly;
498
499 void __init bdev_cache_init(void)
500 {
501         int err;
502         struct vfsmount *bd_mnt;
503
504         bdev_cachep = kmem_cache_create("bdev_cache", sizeof(struct bdev_inode),
505                         0, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
506                                 SLAB_MEM_SPREAD|SLAB_PANIC),
507                         init_once);
508         err = register_filesystem(&bd_type);
509         if (err)
510                 panic("Cannot register bdev pseudo-fs");
511         bd_mnt = kern_mount(&bd_type);
512         if (IS_ERR(bd_mnt))
513                 panic("Cannot create bdev pseudo-fs");
514         /*
515          * This vfsmount structure is only used to obtain the
516          * blockdev_superblock, so tell kmemleak not to report it.
517          */
518         kmemleak_not_leak(bd_mnt);
519         blockdev_superblock = bd_mnt->mnt_sb;   /* For writeback */
520 }
521
522 /*
523  * Most likely _very_ bad one - but then it's hardly critical for small
524  * /dev and can be fixed when somebody will need really large one.
525  * Keep in mind that it will be fed through icache hash function too.
526  */
527 static inline unsigned long hash(dev_t dev)
528 {
529         return MAJOR(dev)+MINOR(dev);
530 }
531
532 static int bdev_test(struct inode *inode, void *data)
533 {
534         return BDEV_I(inode)->bdev.bd_dev == *(dev_t *)data;
535 }
536
537 static int bdev_set(struct inode *inode, void *data)
538 {
539         BDEV_I(inode)->bdev.bd_dev = *(dev_t *)data;
540         return 0;
541 }
542
543 static LIST_HEAD(all_bdevs);
544
545 struct block_device *bdget(dev_t dev)
546 {
547         struct block_device *bdev;
548         struct inode *inode;
549
550         inode = iget5_locked(blockdev_superblock, hash(dev),
551                         bdev_test, bdev_set, &dev);
552
553         if (!inode)
554                 return NULL;
555
556         bdev = &BDEV_I(inode)->bdev;
557
558         if (inode->i_state & I_NEW) {
559                 bdev->bd_contains = NULL;
560                 bdev->bd_super = NULL;
561                 bdev->bd_inode = inode;
562                 bdev->bd_block_size = (1 << inode->i_blkbits);
563                 bdev->bd_part_count = 0;
564                 bdev->bd_invalidated = 0;
565                 inode->i_mode = S_IFBLK;
566                 inode->i_rdev = dev;
567                 inode->i_bdev = bdev;
568                 inode->i_data.a_ops = &def_blk_aops;
569                 mapping_set_gfp_mask(&inode->i_data, GFP_USER);
570                 inode->i_data.backing_dev_info = &default_backing_dev_info;
571                 spin_lock(&bdev_lock);
572                 list_add(&bdev->bd_list, &all_bdevs);
573                 spin_unlock(&bdev_lock);
574                 unlock_new_inode(inode);
575         }
576         return bdev;
577 }
578
579 EXPORT_SYMBOL(bdget);
580
581 /**
582  * bdgrab -- Grab a reference to an already referenced block device
583  * @bdev:       Block device to grab a reference to.
584  */
585 struct block_device *bdgrab(struct block_device *bdev)
586 {
587         ihold(bdev->bd_inode);
588         return bdev;
589 }
590 EXPORT_SYMBOL(bdgrab);
591
592 long nr_blockdev_pages(void)
593 {
594         struct block_device *bdev;
595         long ret = 0;
596         spin_lock(&bdev_lock);
597         list_for_each_entry(bdev, &all_bdevs, bd_list) {
598                 ret += bdev->bd_inode->i_mapping->nrpages;
599         }
600         spin_unlock(&bdev_lock);
601         return ret;
602 }
603
604 void bdput(struct block_device *bdev)
605 {
606         iput(bdev->bd_inode);
607 }
608
609 EXPORT_SYMBOL(bdput);
610  
611 static struct block_device *bd_acquire(struct inode *inode)
612 {
613         struct block_device *bdev;
614
615         spin_lock(&bdev_lock);
616         bdev = inode->i_bdev;
617         if (bdev) {
618                 ihold(bdev->bd_inode);
619                 spin_unlock(&bdev_lock);
620                 return bdev;
621         }
622         spin_unlock(&bdev_lock);
623
624         bdev = bdget(inode->i_rdev);
625         if (bdev) {
626                 spin_lock(&bdev_lock);
627                 if (!inode->i_bdev) {
628                         /*
629                          * We take an additional reference to bd_inode,
630                          * and it's released in clear_inode() of inode.
631                          * So, we can access it via ->i_mapping always
632                          * without igrab().
633                          */
634                         ihold(bdev->bd_inode);
635                         inode->i_bdev = bdev;
636                         inode->i_mapping = bdev->bd_inode->i_mapping;
637                         list_add(&inode->i_devices, &bdev->bd_inodes);
638                 }
639                 spin_unlock(&bdev_lock);
640         }
641         return bdev;
642 }
643
644 /* Call when you free inode */
645
646 void bd_forget(struct inode *inode)
647 {
648         struct block_device *bdev = NULL;
649
650         spin_lock(&bdev_lock);
651         if (inode->i_bdev) {
652                 if (!sb_is_blkdev_sb(inode->i_sb))
653                         bdev = inode->i_bdev;
654                 __bd_forget(inode);
655         }
656         spin_unlock(&bdev_lock);
657
658         if (bdev)
659                 iput(bdev->bd_inode);
660 }
661
662 /**
663  * bd_may_claim - test whether a block device can be claimed
664  * @bdev: block device of interest
665  * @whole: whole block device containing @bdev, may equal @bdev
666  * @holder: holder trying to claim @bdev
667  *
668  * Test whether @bdev can be claimed by @holder.
669  *
670  * CONTEXT:
671  * spin_lock(&bdev_lock).
672  *
673  * RETURNS:
674  * %true if @bdev can be claimed, %false otherwise.
675  */
676 static bool bd_may_claim(struct block_device *bdev, struct block_device *whole,
677                          void *holder)
678 {
679         if (bdev->bd_holder == holder)
680                 return true;     /* already a holder */
681         else if (bdev->bd_holder != NULL)
682                 return false;    /* held by someone else */
683         else if (bdev->bd_contains == bdev)
684                 return true;     /* is a whole device which isn't held */
685
686         else if (whole->bd_holder == bd_may_claim)
687                 return true;     /* is a partition of a device that is being partitioned */
688         else if (whole->bd_holder != NULL)
689                 return false;    /* is a partition of a held device */
690         else
691                 return true;     /* is a partition of an un-held device */
692 }
693
694 /**
695  * bd_prepare_to_claim - prepare to claim a block device
696  * @bdev: block device of interest
697  * @whole: the whole device containing @bdev, may equal @bdev
698  * @holder: holder trying to claim @bdev
699  *
700  * Prepare to claim @bdev.  This function fails if @bdev is already
701  * claimed by another holder and waits if another claiming is in
702  * progress.  This function doesn't actually claim.  On successful
703  * return, the caller has ownership of bd_claiming and bd_holder[s].
704  *
705  * CONTEXT:
706  * spin_lock(&bdev_lock).  Might release bdev_lock, sleep and regrab
707  * it multiple times.
708  *
709  * RETURNS:
710  * 0 if @bdev can be claimed, -EBUSY otherwise.
711  */
712 static int bd_prepare_to_claim(struct block_device *bdev,
713                                struct block_device *whole, void *holder)
714 {
715 retry:
716         /* if someone else claimed, fail */
717         if (!bd_may_claim(bdev, whole, holder))
718                 return -EBUSY;
719
720         /* if claiming is already in progress, wait for it to finish */
721         if (whole->bd_claiming) {
722                 wait_queue_head_t *wq = bit_waitqueue(&whole->bd_claiming, 0);
723                 DEFINE_WAIT(wait);
724
725                 prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
726                 spin_unlock(&bdev_lock);
727                 schedule();
728                 finish_wait(wq, &wait);
729                 spin_lock(&bdev_lock);
730                 goto retry;
731         }
732
733         /* yay, all mine */
734         return 0;
735 }
736
737 /**
738  * bd_start_claiming - start claiming a block device
739  * @bdev: block device of interest
740  * @holder: holder trying to claim @bdev
741  *
742  * @bdev is about to be opened exclusively.  Check @bdev can be opened
743  * exclusively and mark that an exclusive open is in progress.  Each
744  * successful call to this function must be matched with a call to
745  * either bd_finish_claiming() or bd_abort_claiming() (which do not
746  * fail).
747  *
748  * This function is used to gain exclusive access to the block device
749  * without actually causing other exclusive open attempts to fail. It
750  * should be used when the open sequence itself requires exclusive
751  * access but may subsequently fail.
752  *
753  * CONTEXT:
754  * Might sleep.
755  *
756  * RETURNS:
757  * Pointer to the block device containing @bdev on success, ERR_PTR()
758  * value on failure.
759  */
760 static struct block_device *bd_start_claiming(struct block_device *bdev,
761                                               void *holder)
762 {
763         struct gendisk *disk;
764         struct block_device *whole;
765         int partno, err;
766
767         might_sleep();
768
769         /*
770          * @bdev might not have been initialized properly yet, look up
771          * and grab the outer block device the hard way.
772          */
773         disk = get_gendisk(bdev->bd_dev, &partno);
774         if (!disk)
775                 return ERR_PTR(-ENXIO);
776
777         /*
778          * Normally, @bdev should equal what's returned from bdget_disk()
779          * if partno is 0; however, some drivers (floppy) use multiple
780          * bdev's for the same physical device and @bdev may be one of the
781          * aliases.  Keep @bdev if partno is 0.  This means claimer
782          * tracking is broken for those devices but it has always been that
783          * way.
784          */
785         if (partno)
786                 whole = bdget_disk(disk, 0);
787         else
788                 whole = bdgrab(bdev);
789
790         module_put(disk->fops->owner);
791         put_disk(disk);
792         if (!whole)
793                 return ERR_PTR(-ENOMEM);
794
795         /* prepare to claim, if successful, mark claiming in progress */
796         spin_lock(&bdev_lock);
797
798         err = bd_prepare_to_claim(bdev, whole, holder);
799         if (err == 0) {
800                 whole->bd_claiming = holder;
801                 spin_unlock(&bdev_lock);
802                 return whole;
803         } else {
804                 spin_unlock(&bdev_lock);
805                 bdput(whole);
806                 return ERR_PTR(err);
807         }
808 }
809
810 #ifdef CONFIG_SYSFS
811 struct bd_holder_disk {
812         struct list_head        list;
813         struct gendisk          *disk;
814         int                     refcnt;
815 };
816
817 static struct bd_holder_disk *bd_find_holder_disk(struct block_device *bdev,
818                                                   struct gendisk *disk)
819 {
820         struct bd_holder_disk *holder;
821
822         list_for_each_entry(holder, &bdev->bd_holder_disks, list)
823                 if (holder->disk == disk)
824                         return holder;
825         return NULL;
826 }
827
828 static int add_symlink(struct kobject *from, struct kobject *to)
829 {
830         return sysfs_create_link(from, to, kobject_name(to));
831 }
832
833 static void del_symlink(struct kobject *from, struct kobject *to)
834 {
835         sysfs_remove_link(from, kobject_name(to));
836 }
837
838 /**
839  * bd_link_disk_holder - create symlinks between holding disk and slave bdev
840  * @bdev: the claimed slave bdev
841  * @disk: the holding disk
842  *
843  * DON'T USE THIS UNLESS YOU'RE ALREADY USING IT.
844  *
845  * This functions creates the following sysfs symlinks.
846  *
847  * - from "slaves" directory of the holder @disk to the claimed @bdev
848  * - from "holders" directory of the @bdev to the holder @disk
849  *
850  * For example, if /dev/dm-0 maps to /dev/sda and disk for dm-0 is
851  * passed to bd_link_disk_holder(), then:
852  *
853  *   /sys/block/dm-0/slaves/sda --> /sys/block/sda
854  *   /sys/block/sda/holders/dm-0 --> /sys/block/dm-0
855  *
856  * The caller must have claimed @bdev before calling this function and
857  * ensure that both @bdev and @disk are valid during the creation and
858  * lifetime of these symlinks.
859  *
860  * CONTEXT:
861  * Might sleep.
862  *
863  * RETURNS:
864  * 0 on success, -errno on failure.
865  */
866 int bd_link_disk_holder(struct block_device *bdev, struct gendisk *disk)
867 {
868         struct bd_holder_disk *holder;
869         int ret = 0;
870
871         mutex_lock(&bdev->bd_mutex);
872
873         WARN_ON_ONCE(!bdev->bd_holder);
874
875         /* FIXME: remove the following once add_disk() handles errors */
876         if (WARN_ON(!disk->slave_dir || !bdev->bd_part->holder_dir))
877                 goto out_unlock;
878
879         holder = bd_find_holder_disk(bdev, disk);
880         if (holder) {
881                 holder->refcnt++;
882                 goto out_unlock;
883         }
884
885         holder = kzalloc(sizeof(*holder), GFP_KERNEL);
886         if (!holder) {
887                 ret = -ENOMEM;
888                 goto out_unlock;
889         }
890
891         INIT_LIST_HEAD(&holder->list);
892         holder->disk = disk;
893         holder->refcnt = 1;
894
895         ret = add_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
896         if (ret)
897                 goto out_free;
898
899         ret = add_symlink(bdev->bd_part->holder_dir, &disk_to_dev(disk)->kobj);
900         if (ret)
901                 goto out_del;
902         /*
903          * bdev could be deleted beneath us which would implicitly destroy
904          * the holder directory.  Hold on to it.
905          */
906         kobject_get(bdev->bd_part->holder_dir);
907
908         list_add(&holder->list, &bdev->bd_holder_disks);
909         goto out_unlock;
910
911 out_del:
912         del_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
913 out_free:
914         kfree(holder);
915 out_unlock:
916         mutex_unlock(&bdev->bd_mutex);
917         return ret;
918 }
919 EXPORT_SYMBOL_GPL(bd_link_disk_holder);
920
921 /**
922  * bd_unlink_disk_holder - destroy symlinks created by bd_link_disk_holder()
923  * @bdev: the calimed slave bdev
924  * @disk: the holding disk
925  *
926  * DON'T USE THIS UNLESS YOU'RE ALREADY USING IT.
927  *
928  * CONTEXT:
929  * Might sleep.
930  */
931 void bd_unlink_disk_holder(struct block_device *bdev, struct gendisk *disk)
932 {
933         struct bd_holder_disk *holder;
934
935         mutex_lock(&bdev->bd_mutex);
936
937         holder = bd_find_holder_disk(bdev, disk);
938
939         if (!WARN_ON_ONCE(holder == NULL) && !--holder->refcnt) {
940                 del_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
941                 del_symlink(bdev->bd_part->holder_dir,
942                             &disk_to_dev(disk)->kobj);
943                 kobject_put(bdev->bd_part->holder_dir);
944                 list_del_init(&holder->list);
945                 kfree(holder);
946         }
947
948         mutex_unlock(&bdev->bd_mutex);
949 }
950 EXPORT_SYMBOL_GPL(bd_unlink_disk_holder);
951 #endif
952
953 /**
954  * flush_disk - invalidates all buffer-cache entries on a disk
955  *
956  * @bdev:      struct block device to be flushed
957  * @kill_dirty: flag to guide handling of dirty inodes
958  *
959  * Invalidates all buffer-cache entries on a disk. It should be called
960  * when a disk has been changed -- either by a media change or online
961  * resize.
962  */
963 static void flush_disk(struct block_device *bdev, bool kill_dirty)
964 {
965         if (__invalidate_device(bdev, kill_dirty)) {
966                 char name[BDEVNAME_SIZE] = "";
967
968                 if (bdev->bd_disk)
969                         disk_name(bdev->bd_disk, 0, name);
970                 printk(KERN_WARNING "VFS: busy inodes on changed media or "
971                        "resized disk %s\n", name);
972         }
973
974         if (!bdev->bd_disk)
975                 return;
976         if (disk_part_scan_enabled(bdev->bd_disk))
977                 bdev->bd_invalidated = 1;
978 }
979
980 /**
981  * check_disk_size_change - checks for disk size change and adjusts bdev size.
982  * @disk: struct gendisk to check
983  * @bdev: struct bdev to adjust.
984  *
985  * This routine checks to see if the bdev size does not match the disk size
986  * and adjusts it if it differs.
987  */
988 void check_disk_size_change(struct gendisk *disk, struct block_device *bdev)
989 {
990         loff_t disk_size, bdev_size;
991
992         disk_size = (loff_t)get_capacity(disk) << 9;
993         bdev_size = i_size_read(bdev->bd_inode);
994         if (disk_size != bdev_size) {
995                 char name[BDEVNAME_SIZE];
996
997                 disk_name(disk, 0, name);
998                 printk(KERN_INFO
999                        "%s: detected capacity change from %lld to %lld\n",
1000                        name, bdev_size, disk_size);
1001                 i_size_write(bdev->bd_inode, disk_size);
1002                 flush_disk(bdev, false);
1003         }
1004 }
1005 EXPORT_SYMBOL(check_disk_size_change);
1006
1007 /**
1008  * revalidate_disk - wrapper for lower-level driver's revalidate_disk call-back
1009  * @disk: struct gendisk to be revalidated
1010  *
1011  * This routine is a wrapper for lower-level driver's revalidate_disk
1012  * call-backs.  It is used to do common pre and post operations needed
1013  * for all revalidate_disk operations.
1014  */
1015 int revalidate_disk(struct gendisk *disk)
1016 {
1017         struct block_device *bdev;
1018         int ret = 0;
1019
1020         if (disk->fops->revalidate_disk)
1021                 ret = disk->fops->revalidate_disk(disk);
1022
1023         bdev = bdget_disk(disk, 0);
1024         if (!bdev)
1025                 return ret;
1026
1027         mutex_lock(&bdev->bd_mutex);
1028         check_disk_size_change(disk, bdev);
1029         bdev->bd_invalidated = 0;
1030         mutex_unlock(&bdev->bd_mutex);
1031         bdput(bdev);
1032         return ret;
1033 }
1034 EXPORT_SYMBOL(revalidate_disk);
1035
1036 /*
1037  * This routine checks whether a removable media has been changed,
1038  * and invalidates all buffer-cache-entries in that case. This
1039  * is a relatively slow routine, so we have to try to minimize using
1040  * it. Thus it is called only upon a 'mount' or 'open'. This
1041  * is the best way of combining speed and utility, I think.
1042  * People changing diskettes in the middle of an operation deserve
1043  * to lose :-)
1044  */
1045 int check_disk_change(struct block_device *bdev)
1046 {
1047         struct gendisk *disk = bdev->bd_disk;
1048         const struct block_device_operations *bdops = disk->fops;
1049         unsigned int events;
1050
1051         events = disk_clear_events(disk, DISK_EVENT_MEDIA_CHANGE |
1052                                    DISK_EVENT_EJECT_REQUEST);
1053         if (!(events & DISK_EVENT_MEDIA_CHANGE))
1054                 return 0;
1055
1056         flush_disk(bdev, true);
1057         if (bdops->revalidate_disk)
1058                 bdops->revalidate_disk(bdev->bd_disk);
1059         return 1;
1060 }
1061
1062 EXPORT_SYMBOL(check_disk_change);
1063
1064 void bd_set_size(struct block_device *bdev, loff_t size)
1065 {
1066         unsigned bsize = bdev_logical_block_size(bdev);
1067
1068         mutex_lock(&bdev->bd_inode->i_mutex);
1069         i_size_write(bdev->bd_inode, size);
1070         mutex_unlock(&bdev->bd_inode->i_mutex);
1071         while (bsize < PAGE_CACHE_SIZE) {
1072                 if (size & bsize)
1073                         break;
1074                 bsize <<= 1;
1075         }
1076         bdev->bd_block_size = bsize;
1077         bdev->bd_inode->i_blkbits = blksize_bits(bsize);
1078 }
1079 EXPORT_SYMBOL(bd_set_size);
1080
1081 static int __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part);
1082
1083 /*
1084  * bd_mutex locking:
1085  *
1086  *  mutex_lock(part->bd_mutex)
1087  *    mutex_lock_nested(whole->bd_mutex, 1)
1088  */
1089
1090 static int __blkdev_get(struct block_device *bdev, fmode_t mode, int for_part)
1091 {
1092         struct gendisk *disk;
1093         struct module *owner;
1094         int ret;
1095         int partno;
1096         int perm = 0;
1097
1098         if (mode & FMODE_READ)
1099                 perm |= MAY_READ;
1100         if (mode & FMODE_WRITE)
1101                 perm |= MAY_WRITE;
1102         /*
1103          * hooks: /n/, see "layering violations".
1104          */
1105         if (!for_part) {
1106                 ret = devcgroup_inode_permission(bdev->bd_inode, perm);
1107                 if (ret != 0) {
1108                         bdput(bdev);
1109                         return ret;
1110                 }
1111         }
1112
1113  restart:
1114
1115         ret = -ENXIO;
1116         disk = get_gendisk(bdev->bd_dev, &partno);
1117         if (!disk)
1118                 goto out;
1119         owner = disk->fops->owner;
1120
1121         disk_block_events(disk);
1122         mutex_lock_nested(&bdev->bd_mutex, for_part);
1123         if (!bdev->bd_openers) {
1124                 bdev->bd_disk = disk;
1125                 bdev->bd_contains = bdev;
1126                 if (!partno) {
1127                         struct backing_dev_info *bdi;
1128
1129                         ret = -ENXIO;
1130                         bdev->bd_part = disk_get_part(disk, partno);
1131                         if (!bdev->bd_part)
1132                                 goto out_clear;
1133
1134                         ret = 0;
1135                         if (disk->fops->open) {
1136                                 ret = disk->fops->open(bdev, mode);
1137                                 if (ret == -ERESTARTSYS) {
1138                                         /* Lost a race with 'disk' being
1139                                          * deleted, try again.
1140                                          * See md.c
1141                                          */
1142                                         disk_put_part(bdev->bd_part);
1143                                         bdev->bd_part = NULL;
1144                                         bdev->bd_disk = NULL;
1145                                         mutex_unlock(&bdev->bd_mutex);
1146                                         disk_unblock_events(disk);
1147                                         put_disk(disk);
1148                                         module_put(owner);
1149                                         goto restart;
1150                                 }
1151                         }
1152
1153                         if (!ret && !bdev->bd_openers) {
1154                                 bd_set_size(bdev,(loff_t)get_capacity(disk)<<9);
1155                                 bdi = blk_get_backing_dev_info(bdev);
1156                                 if (bdi == NULL)
1157                                         bdi = &default_backing_dev_info;
1158                                 bdev_inode_switch_bdi(bdev->bd_inode, bdi);
1159                         }
1160
1161                         /*
1162                          * If the device is invalidated, rescan partition
1163                          * if open succeeded or failed with -ENOMEDIUM.
1164                          * The latter is necessary to prevent ghost
1165                          * partitions on a removed medium.
1166                          */
1167                         if (bdev->bd_invalidated) {
1168                                 if (!ret)
1169                                         rescan_partitions(disk, bdev);
1170                                 else if (ret == -ENOMEDIUM)
1171                                         invalidate_partitions(disk, bdev);
1172                         }
1173                         if (ret)
1174                                 goto out_clear;
1175                 } else {
1176                         struct block_device *whole;
1177                         whole = bdget_disk(disk, 0);
1178                         ret = -ENOMEM;
1179                         if (!whole)
1180                                 goto out_clear;
1181                         BUG_ON(for_part);
1182                         ret = __blkdev_get(whole, mode, 1);
1183                         if (ret)
1184                                 goto out_clear;
1185                         bdev->bd_contains = whole;
1186                         bdev_inode_switch_bdi(bdev->bd_inode,
1187                                 whole->bd_inode->i_data.backing_dev_info);
1188                         bdev->bd_part = disk_get_part(disk, partno);
1189                         if (!(disk->flags & GENHD_FL_UP) ||
1190                             !bdev->bd_part || !bdev->bd_part->nr_sects) {
1191                                 ret = -ENXIO;
1192                                 goto out_clear;
1193                         }
1194                         bd_set_size(bdev, (loff_t)bdev->bd_part->nr_sects << 9);
1195                 }
1196         } else {
1197                 if (bdev->bd_contains == bdev) {
1198                         ret = 0;
1199                         if (bdev->bd_disk->fops->open)
1200                                 ret = bdev->bd_disk->fops->open(bdev, mode);
1201                         /* the same as first opener case, read comment there */
1202                         if (bdev->bd_invalidated) {
1203                                 if (!ret)
1204                                         rescan_partitions(bdev->bd_disk, bdev);
1205                                 else if (ret == -ENOMEDIUM)
1206                                         invalidate_partitions(bdev->bd_disk, bdev);
1207                         }
1208                         if (ret)
1209                                 goto out_unlock_bdev;
1210                 }
1211                 /* only one opener holds refs to the module and disk */
1212                 put_disk(disk);
1213                 module_put(owner);
1214         }
1215         bdev->bd_openers++;
1216         if (for_part)
1217                 bdev->bd_part_count++;
1218         mutex_unlock(&bdev->bd_mutex);
1219         disk_unblock_events(disk);
1220         return 0;
1221
1222  out_clear:
1223         disk_put_part(bdev->bd_part);
1224         bdev->bd_disk = NULL;
1225         bdev->bd_part = NULL;
1226         bdev_inode_switch_bdi(bdev->bd_inode, &default_backing_dev_info);
1227         if (bdev != bdev->bd_contains)
1228                 __blkdev_put(bdev->bd_contains, mode, 1);
1229         bdev->bd_contains = NULL;
1230  out_unlock_bdev:
1231         mutex_unlock(&bdev->bd_mutex);
1232         disk_unblock_events(disk);
1233         put_disk(disk);
1234         module_put(owner);
1235  out:
1236         bdput(bdev);
1237
1238         return ret;
1239 }
1240
1241 /**
1242  * blkdev_get - open a block device
1243  * @bdev: block_device to open
1244  * @mode: FMODE_* mask
1245  * @holder: exclusive holder identifier
1246  *
1247  * Open @bdev with @mode.  If @mode includes %FMODE_EXCL, @bdev is
1248  * open with exclusive access.  Specifying %FMODE_EXCL with %NULL
1249  * @holder is invalid.  Exclusive opens may nest for the same @holder.
1250  *
1251  * On success, the reference count of @bdev is unchanged.  On failure,
1252  * @bdev is put.
1253  *
1254  * CONTEXT:
1255  * Might sleep.
1256  *
1257  * RETURNS:
1258  * 0 on success, -errno on failure.
1259  */
1260 int blkdev_get(struct block_device *bdev, fmode_t mode, void *holder)
1261 {
1262         struct block_device *whole = NULL;
1263         int res;
1264
1265         WARN_ON_ONCE((mode & FMODE_EXCL) && !holder);
1266
1267         if ((mode & FMODE_EXCL) && holder) {
1268                 whole = bd_start_claiming(bdev, holder);
1269                 if (IS_ERR(whole)) {
1270                         bdput(bdev);
1271                         return PTR_ERR(whole);
1272                 }
1273         }
1274
1275         res = __blkdev_get(bdev, mode, 0);
1276
1277         if (whole) {
1278                 struct gendisk *disk = whole->bd_disk;
1279
1280                 /* finish claiming */
1281                 mutex_lock(&bdev->bd_mutex);
1282                 spin_lock(&bdev_lock);
1283
1284                 if (!res) {
1285                         BUG_ON(!bd_may_claim(bdev, whole, holder));
1286                         /*
1287                          * Note that for a whole device bd_holders
1288                          * will be incremented twice, and bd_holder
1289                          * will be set to bd_may_claim before being
1290                          * set to holder
1291                          */
1292                         whole->bd_holders++;
1293                         whole->bd_holder = bd_may_claim;
1294                         bdev->bd_holders++;
1295                         bdev->bd_holder = holder;
1296                 }
1297
1298                 /* tell others that we're done */
1299                 BUG_ON(whole->bd_claiming != holder);
1300                 whole->bd_claiming = NULL;
1301                 wake_up_bit(&whole->bd_claiming, 0);
1302
1303                 spin_unlock(&bdev_lock);
1304
1305                 /*
1306                  * Block event polling for write claims if requested.  Any
1307                  * write holder makes the write_holder state stick until
1308                  * all are released.  This is good enough and tracking
1309                  * individual writeable reference is too fragile given the
1310                  * way @mode is used in blkdev_get/put().
1311                  */
1312                 if (!res && (mode & FMODE_WRITE) && !bdev->bd_write_holder &&
1313                     (disk->flags & GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE)) {
1314                         bdev->bd_write_holder = true;
1315                         disk_block_events(disk);
1316                 }
1317
1318                 mutex_unlock(&bdev->bd_mutex);
1319                 bdput(whole);
1320         }
1321
1322         return res;
1323 }
1324 EXPORT_SYMBOL(blkdev_get);
1325
1326 /**
1327  * blkdev_get_by_path - open a block device by name
1328  * @path: path to the block device to open
1329  * @mode: FMODE_* mask
1330  * @holder: exclusive holder identifier
1331  *
1332  * Open the blockdevice described by the device file at @path.  @mode
1333  * and @holder are identical to blkdev_get().
1334  *
1335  * On success, the returned block_device has reference count of one.
1336  *
1337  * CONTEXT:
1338  * Might sleep.
1339  *
1340  * RETURNS:
1341  * Pointer to block_device on success, ERR_PTR(-errno) on failure.
1342  */
1343 struct block_device *blkdev_get_by_path(const char *path, fmode_t mode,
1344                                         void *holder)
1345 {
1346         struct block_device *bdev;
1347         int err;
1348
1349         bdev = lookup_bdev(path);
1350         if (IS_ERR(bdev))
1351                 return bdev;
1352
1353         err = blkdev_get(bdev, mode, holder);
1354         if (err)
1355                 return ERR_PTR(err);
1356
1357         if ((mode & FMODE_WRITE) && bdev_read_only(bdev)) {
1358                 blkdev_put(bdev, mode);
1359                 return ERR_PTR(-EACCES);
1360         }
1361
1362         return bdev;
1363 }
1364 EXPORT_SYMBOL(blkdev_get_by_path);
1365
1366 /**
1367  * blkdev_get_by_dev - open a block device by device number
1368  * @dev: device number of block device to open
1369  * @mode: FMODE_* mask
1370  * @holder: exclusive holder identifier
1371  *
1372  * Open the blockdevice described by device number @dev.  @mode and
1373  * @holder are identical to blkdev_get().
1374  *
1375  * Use it ONLY if you really do not have anything better - i.e. when
1376  * you are behind a truly sucky interface and all you are given is a
1377  * device number.  _Never_ to be used for internal purposes.  If you
1378  * ever need it - reconsider your API.
1379  *
1380  * On success, the returned block_device has reference count of one.
1381  *
1382  * CONTEXT:
1383  * Might sleep.
1384  *
1385  * RETURNS:
1386  * Pointer to block_device on success, ERR_PTR(-errno) on failure.
1387  */
1388 struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode, void *holder)
1389 {
1390         struct block_device *bdev;
1391         int err;
1392
1393         bdev = bdget(dev);
1394         if (!bdev)
1395                 return ERR_PTR(-ENOMEM);
1396
1397         err = blkdev_get(bdev, mode, holder);
1398         if (err)
1399                 return ERR_PTR(err);
1400
1401         return bdev;
1402 }
1403 EXPORT_SYMBOL(blkdev_get_by_dev);
1404
1405 static int blkdev_open(struct inode * inode, struct file * filp)
1406 {
1407         struct block_device *bdev;
1408
1409         /*
1410          * Preserve backwards compatibility and allow large file access
1411          * even if userspace doesn't ask for it explicitly. Some mkfs
1412          * binary needs it. We might want to drop this workaround
1413          * during an unstable branch.
1414          */
1415         filp->f_flags |= O_LARGEFILE;
1416
1417         if (filp->f_flags & O_NDELAY)
1418                 filp->f_mode |= FMODE_NDELAY;
1419         if (filp->f_flags & O_EXCL)
1420                 filp->f_mode |= FMODE_EXCL;
1421         if ((filp->f_flags & O_ACCMODE) == 3)
1422                 filp->f_mode |= FMODE_WRITE_IOCTL;
1423
1424         bdev = bd_acquire(inode);
1425         if (bdev == NULL)
1426                 return -ENOMEM;
1427
1428         filp->f_mapping = bdev->bd_inode->i_mapping;
1429
1430         return blkdev_get(bdev, filp->f_mode, filp);
1431 }
1432
1433 static int __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part)
1434 {
1435         int ret = 0;
1436         struct gendisk *disk = bdev->bd_disk;
1437         struct block_device *victim = NULL;
1438
1439         mutex_lock_nested(&bdev->bd_mutex, for_part);
1440         if (for_part)
1441                 bdev->bd_part_count--;
1442
1443         if (!--bdev->bd_openers) {
1444                 WARN_ON_ONCE(bdev->bd_holders);
1445                 sync_blockdev(bdev);
1446                 kill_bdev(bdev);
1447                 /* ->release can cause the old bdi to disappear,
1448                  * so must switch it out first
1449                  */
1450                 bdev_inode_switch_bdi(bdev->bd_inode,
1451                                         &default_backing_dev_info);
1452         }
1453         if (bdev->bd_contains == bdev) {
1454                 if (disk->fops->release)
1455                         ret = disk->fops->release(disk, mode);
1456         }
1457         if (!bdev->bd_openers) {
1458                 struct module *owner = disk->fops->owner;
1459
1460                 disk_put_part(bdev->bd_part);
1461                 bdev->bd_part = NULL;
1462                 bdev->bd_disk = NULL;
1463                 if (bdev != bdev->bd_contains)
1464                         victim = bdev->bd_contains;
1465                 bdev->bd_contains = NULL;
1466
1467                 put_disk(disk);
1468                 module_put(owner);
1469         }
1470         mutex_unlock(&bdev->bd_mutex);
1471         bdput(bdev);
1472         if (victim)
1473                 __blkdev_put(victim, mode, 1);
1474         return ret;
1475 }
1476
1477 int blkdev_put(struct block_device *bdev, fmode_t mode)
1478 {
1479         mutex_lock(&bdev->bd_mutex);
1480
1481         if (mode & FMODE_EXCL) {
1482                 bool bdev_free;
1483
1484                 /*
1485                  * Release a claim on the device.  The holder fields
1486                  * are protected with bdev_lock.  bd_mutex is to
1487                  * synchronize disk_holder unlinking.
1488                  */
1489                 spin_lock(&bdev_lock);
1490
1491                 WARN_ON_ONCE(--bdev->bd_holders < 0);
1492                 WARN_ON_ONCE(--bdev->bd_contains->bd_holders < 0);
1493
1494                 /* bd_contains might point to self, check in a separate step */
1495                 if ((bdev_free = !bdev->bd_holders))
1496                         bdev->bd_holder = NULL;
1497                 if (!bdev->bd_contains->bd_holders)
1498                         bdev->bd_contains->bd_holder = NULL;
1499
1500                 spin_unlock(&bdev_lock);
1501
1502                 /*
1503                  * If this was the last claim, remove holder link and
1504                  * unblock evpoll if it was a write holder.
1505                  */
1506                 if (bdev_free && bdev->bd_write_holder) {
1507                         disk_unblock_events(bdev->bd_disk);
1508                         bdev->bd_write_holder = false;
1509                 }
1510         }
1511
1512         /*
1513          * Trigger event checking and tell drivers to flush MEDIA_CHANGE
1514          * event.  This is to ensure detection of media removal commanded
1515          * from userland - e.g. eject(1).
1516          */
1517         disk_flush_events(bdev->bd_disk, DISK_EVENT_MEDIA_CHANGE);
1518
1519         mutex_unlock(&bdev->bd_mutex);
1520
1521         return __blkdev_put(bdev, mode, 0);
1522 }
1523 EXPORT_SYMBOL(blkdev_put);
1524
1525 static int blkdev_close(struct inode * inode, struct file * filp)
1526 {
1527         struct block_device *bdev = I_BDEV(filp->f_mapping->host);
1528
1529         return blkdev_put(bdev, filp->f_mode);
1530 }
1531
1532 static long block_ioctl(struct file *file, unsigned cmd, unsigned long arg)
1533 {
1534         struct block_device *bdev = I_BDEV(file->f_mapping->host);
1535         fmode_t mode = file->f_mode;
1536
1537         /*
1538          * O_NDELAY can be altered using fcntl(.., F_SETFL, ..), so we have
1539          * to updated it before every ioctl.
1540          */
1541         if (file->f_flags & O_NDELAY)
1542                 mode |= FMODE_NDELAY;
1543         else
1544                 mode &= ~FMODE_NDELAY;
1545
1546         return blkdev_ioctl(bdev, mode, cmd, arg);
1547 }
1548
1549 /*
1550  * Write data to the block device.  Only intended for the block device itself
1551  * and the raw driver which basically is a fake block device.
1552  *
1553  * Does not take i_mutex for the write and thus is not for general purpose
1554  * use.
1555  */
1556 ssize_t blkdev_aio_write(struct kiocb *iocb, const struct iovec *iov,
1557                          unsigned long nr_segs, loff_t pos)
1558 {
1559         struct file *file = iocb->ki_filp;
1560         ssize_t ret;
1561
1562         BUG_ON(iocb->ki_pos != pos);
1563
1564         ret = __generic_file_aio_write(iocb, iov, nr_segs, &iocb->ki_pos);
1565         if (ret > 0 || ret == -EIOCBQUEUED) {
1566                 ssize_t err;
1567
1568                 err = generic_write_sync(file, pos, ret);
1569                 if (err < 0 && ret > 0)
1570                         ret = err;
1571         }
1572         return ret;
1573 }
1574 EXPORT_SYMBOL_GPL(blkdev_aio_write);
1575
1576 /*
1577  * Try to release a page associated with block device when the system
1578  * is under memory pressure.
1579  */
1580 static int blkdev_releasepage(struct page *page, gfp_t wait)
1581 {
1582         struct super_block *super = BDEV_I(page->mapping->host)->bdev.bd_super;
1583
1584         if (super && super->s_op->bdev_try_to_free_page)
1585                 return super->s_op->bdev_try_to_free_page(super, page, wait);
1586
1587         return try_to_free_buffers(page);
1588 }
1589
1590 static const struct address_space_operations def_blk_aops = {
1591         .readpage       = blkdev_readpage,
1592         .writepage      = blkdev_writepage,
1593         .write_begin    = blkdev_write_begin,
1594         .write_end      = blkdev_write_end,
1595         .writepages     = generic_writepages,
1596         .releasepage    = blkdev_releasepage,
1597         .direct_IO      = blkdev_direct_IO,
1598 };
1599
1600 const struct file_operations def_blk_fops = {
1601         .open           = blkdev_open,
1602         .release        = blkdev_close,
1603         .llseek         = block_llseek,
1604         .read           = do_sync_read,
1605         .write          = do_sync_write,
1606         .aio_read       = generic_file_aio_read,
1607         .aio_write      = blkdev_aio_write,
1608         .mmap           = generic_file_mmap,
1609         .fsync          = blkdev_fsync,
1610         .unlocked_ioctl = block_ioctl,
1611 #ifdef CONFIG_COMPAT
1612         .compat_ioctl   = compat_blkdev_ioctl,
1613 #endif
1614         .splice_read    = generic_file_splice_read,
1615         .splice_write   = generic_file_splice_write,
1616 };
1617
1618 int ioctl_by_bdev(struct block_device *bdev, unsigned cmd, unsigned long arg)
1619 {
1620         int res;
1621         mm_segment_t old_fs = get_fs();
1622         set_fs(KERNEL_DS);
1623         res = blkdev_ioctl(bdev, 0, cmd, arg);
1624         set_fs(old_fs);
1625         return res;
1626 }
1627
1628 EXPORT_SYMBOL(ioctl_by_bdev);
1629
1630 /**
1631  * lookup_bdev  - lookup a struct block_device by name
1632  * @pathname:   special file representing the block device
1633  *
1634  * Get a reference to the blockdevice at @pathname in the current
1635  * namespace if possible and return it.  Return ERR_PTR(error)
1636  * otherwise.
1637  */
1638 struct block_device *lookup_bdev(const char *pathname)
1639 {
1640         struct block_device *bdev;
1641         struct inode *inode;
1642         struct path path;
1643         int error;
1644
1645         if (!pathname || !*pathname)
1646                 return ERR_PTR(-EINVAL);
1647
1648         error = kern_path(pathname, LOOKUP_FOLLOW, &path);
1649         if (error)
1650                 return ERR_PTR(error);
1651
1652         inode = path.dentry->d_inode;
1653         error = -ENOTBLK;
1654         if (!S_ISBLK(inode->i_mode))
1655                 goto fail;
1656         error = -EACCES;
1657         if (path.mnt->mnt_flags & MNT_NODEV)
1658                 goto fail;
1659         error = -ENOMEM;
1660         bdev = bd_acquire(inode);
1661         if (!bdev)
1662                 goto fail;
1663 out:
1664         path_put(&path);
1665         return bdev;
1666 fail:
1667         bdev = ERR_PTR(error);
1668         goto out;
1669 }
1670 EXPORT_SYMBOL(lookup_bdev);
1671
1672 int __invalidate_device(struct block_device *bdev, bool kill_dirty)
1673 {
1674         struct super_block *sb = get_super(bdev);
1675         int res = 0;
1676
1677         if (sb) {
1678                 /*
1679                  * no need to lock the super, get_super holds the
1680                  * read mutex so the filesystem cannot go away
1681                  * under us (->put_super runs with the write lock
1682                  * hold).
1683                  */
1684                 shrink_dcache_sb(sb);
1685                 res = invalidate_inodes(sb, kill_dirty);
1686                 drop_super(sb);
1687         }
1688         invalidate_bdev(bdev);
1689         return res;
1690 }
1691 EXPORT_SYMBOL(__invalidate_device);