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