833dddb5d65970e6cf108b782fbdca350535c9f9
[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
591 long nr_blockdev_pages(void)
592 {
593         struct block_device *bdev;
594         long ret = 0;
595         spin_lock(&bdev_lock);
596         list_for_each_entry(bdev, &all_bdevs, bd_list) {
597                 ret += bdev->bd_inode->i_mapping->nrpages;
598         }
599         spin_unlock(&bdev_lock);
600         return ret;
601 }
602
603 void bdput(struct block_device *bdev)
604 {
605         iput(bdev->bd_inode);
606 }
607
608 EXPORT_SYMBOL(bdput);
609  
610 static struct block_device *bd_acquire(struct inode *inode)
611 {
612         struct block_device *bdev;
613
614         spin_lock(&bdev_lock);
615         bdev = inode->i_bdev;
616         if (bdev) {
617                 ihold(bdev->bd_inode);
618                 spin_unlock(&bdev_lock);
619                 return bdev;
620         }
621         spin_unlock(&bdev_lock);
622
623         bdev = bdget(inode->i_rdev);
624         if (bdev) {
625                 spin_lock(&bdev_lock);
626                 if (!inode->i_bdev) {
627                         /*
628                          * We take an additional reference to bd_inode,
629                          * and it's released in clear_inode() of inode.
630                          * So, we can access it via ->i_mapping always
631                          * without igrab().
632                          */
633                         ihold(bdev->bd_inode);
634                         inode->i_bdev = bdev;
635                         inode->i_mapping = bdev->bd_inode->i_mapping;
636                         list_add(&inode->i_devices, &bdev->bd_inodes);
637                 }
638                 spin_unlock(&bdev_lock);
639         }
640         return bdev;
641 }
642
643 /* Call when you free inode */
644
645 void bd_forget(struct inode *inode)
646 {
647         struct block_device *bdev = NULL;
648
649         spin_lock(&bdev_lock);
650         if (inode->i_bdev) {
651                 if (!sb_is_blkdev_sb(inode->i_sb))
652                         bdev = inode->i_bdev;
653                 __bd_forget(inode);
654         }
655         spin_unlock(&bdev_lock);
656
657         if (bdev)
658                 iput(bdev->bd_inode);
659 }
660
661 /**
662  * bd_may_claim - test whether a block device can be claimed
663  * @bdev: block device of interest
664  * @whole: whole block device containing @bdev, may equal @bdev
665  * @holder: holder trying to claim @bdev
666  *
667  * Test whether @bdev can be claimed by @holder.
668  *
669  * CONTEXT:
670  * spin_lock(&bdev_lock).
671  *
672  * RETURNS:
673  * %true if @bdev can be claimed, %false otherwise.
674  */
675 static bool bd_may_claim(struct block_device *bdev, struct block_device *whole,
676                          void *holder)
677 {
678         if (bdev->bd_holder == holder)
679                 return true;     /* already a holder */
680         else if (bdev->bd_holder != NULL)
681                 return false;    /* held by someone else */
682         else if (bdev->bd_contains == bdev)
683                 return true;     /* is a whole device which isn't held */
684
685         else if (whole->bd_holder == bd_may_claim)
686                 return true;     /* is a partition of a device that is being partitioned */
687         else if (whole->bd_holder != NULL)
688                 return false;    /* is a partition of a held device */
689         else
690                 return true;     /* is a partition of an un-held device */
691 }
692
693 /**
694  * bd_prepare_to_claim - prepare to claim a block device
695  * @bdev: block device of interest
696  * @whole: the whole device containing @bdev, may equal @bdev
697  * @holder: holder trying to claim @bdev
698  *
699  * Prepare to claim @bdev.  This function fails if @bdev is already
700  * claimed by another holder and waits if another claiming is in
701  * progress.  This function doesn't actually claim.  On successful
702  * return, the caller has ownership of bd_claiming and bd_holder[s].
703  *
704  * CONTEXT:
705  * spin_lock(&bdev_lock).  Might release bdev_lock, sleep and regrab
706  * it multiple times.
707  *
708  * RETURNS:
709  * 0 if @bdev can be claimed, -EBUSY otherwise.
710  */
711 static int bd_prepare_to_claim(struct block_device *bdev,
712                                struct block_device *whole, void *holder)
713 {
714 retry:
715         /* if someone else claimed, fail */
716         if (!bd_may_claim(bdev, whole, holder))
717                 return -EBUSY;
718
719         /* if claiming is already in progress, wait for it to finish */
720         if (whole->bd_claiming) {
721                 wait_queue_head_t *wq = bit_waitqueue(&whole->bd_claiming, 0);
722                 DEFINE_WAIT(wait);
723
724                 prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
725                 spin_unlock(&bdev_lock);
726                 schedule();
727                 finish_wait(wq, &wait);
728                 spin_lock(&bdev_lock);
729                 goto retry;
730         }
731
732         /* yay, all mine */
733         return 0;
734 }
735
736 /**
737  * bd_start_claiming - start claiming a block device
738  * @bdev: block device of interest
739  * @holder: holder trying to claim @bdev
740  *
741  * @bdev is about to be opened exclusively.  Check @bdev can be opened
742  * exclusively and mark that an exclusive open is in progress.  Each
743  * successful call to this function must be matched with a call to
744  * either bd_finish_claiming() or bd_abort_claiming() (which do not
745  * fail).
746  *
747  * This function is used to gain exclusive access to the block device
748  * without actually causing other exclusive open attempts to fail. It
749  * should be used when the open sequence itself requires exclusive
750  * access but may subsequently fail.
751  *
752  * CONTEXT:
753  * Might sleep.
754  *
755  * RETURNS:
756  * Pointer to the block device containing @bdev on success, ERR_PTR()
757  * value on failure.
758  */
759 static struct block_device *bd_start_claiming(struct block_device *bdev,
760                                               void *holder)
761 {
762         struct gendisk *disk;
763         struct block_device *whole;
764         int partno, err;
765
766         might_sleep();
767
768         /*
769          * @bdev might not have been initialized properly yet, look up
770          * and grab the outer block device the hard way.
771          */
772         disk = get_gendisk(bdev->bd_dev, &partno);
773         if (!disk)
774                 return ERR_PTR(-ENXIO);
775
776         /*
777          * Normally, @bdev should equal what's returned from bdget_disk()
778          * if partno is 0; however, some drivers (floppy) use multiple
779          * bdev's for the same physical device and @bdev may be one of the
780          * aliases.  Keep @bdev if partno is 0.  This means claimer
781          * tracking is broken for those devices but it has always been that
782          * way.
783          */
784         if (partno)
785                 whole = bdget_disk(disk, 0);
786         else
787                 whole = bdgrab(bdev);
788
789         module_put(disk->fops->owner);
790         put_disk(disk);
791         if (!whole)
792                 return ERR_PTR(-ENOMEM);
793
794         /* prepare to claim, if successful, mark claiming in progress */
795         spin_lock(&bdev_lock);
796
797         err = bd_prepare_to_claim(bdev, whole, holder);
798         if (err == 0) {
799                 whole->bd_claiming = holder;
800                 spin_unlock(&bdev_lock);
801                 return whole;
802         } else {
803                 spin_unlock(&bdev_lock);
804                 bdput(whole);
805                 return ERR_PTR(err);
806         }
807 }
808
809 #ifdef CONFIG_SYSFS
810 struct bd_holder_disk {
811         struct list_head        list;
812         struct gendisk          *disk;
813         int                     refcnt;
814 };
815
816 static struct bd_holder_disk *bd_find_holder_disk(struct block_device *bdev,
817                                                   struct gendisk *disk)
818 {
819         struct bd_holder_disk *holder;
820
821         list_for_each_entry(holder, &bdev->bd_holder_disks, list)
822                 if (holder->disk == disk)
823                         return holder;
824         return NULL;
825 }
826
827 static int add_symlink(struct kobject *from, struct kobject *to)
828 {
829         return sysfs_create_link(from, to, kobject_name(to));
830 }
831
832 static void del_symlink(struct kobject *from, struct kobject *to)
833 {
834         sysfs_remove_link(from, kobject_name(to));
835 }
836
837 /**
838  * bd_link_disk_holder - create symlinks between holding disk and slave bdev
839  * @bdev: the claimed slave bdev
840  * @disk: the holding disk
841  *
842  * DON'T USE THIS UNLESS YOU'RE ALREADY USING IT.
843  *
844  * This functions creates the following sysfs symlinks.
845  *
846  * - from "slaves" directory of the holder @disk to the claimed @bdev
847  * - from "holders" directory of the @bdev to the holder @disk
848  *
849  * For example, if /dev/dm-0 maps to /dev/sda and disk for dm-0 is
850  * passed to bd_link_disk_holder(), then:
851  *
852  *   /sys/block/dm-0/slaves/sda --> /sys/block/sda
853  *   /sys/block/sda/holders/dm-0 --> /sys/block/dm-0
854  *
855  * The caller must have claimed @bdev before calling this function and
856  * ensure that both @bdev and @disk are valid during the creation and
857  * lifetime of these symlinks.
858  *
859  * CONTEXT:
860  * Might sleep.
861  *
862  * RETURNS:
863  * 0 on success, -errno on failure.
864  */
865 int bd_link_disk_holder(struct block_device *bdev, struct gendisk *disk)
866 {
867         struct bd_holder_disk *holder;
868         int ret = 0;
869
870         mutex_lock(&bdev->bd_mutex);
871
872         WARN_ON_ONCE(!bdev->bd_holder);
873
874         /* FIXME: remove the following once add_disk() handles errors */
875         if (WARN_ON(!disk->slave_dir || !bdev->bd_part->holder_dir))
876                 goto out_unlock;
877
878         holder = bd_find_holder_disk(bdev, disk);
879         if (holder) {
880                 holder->refcnt++;
881                 goto out_unlock;
882         }
883
884         holder = kzalloc(sizeof(*holder), GFP_KERNEL);
885         if (!holder) {
886                 ret = -ENOMEM;
887                 goto out_unlock;
888         }
889
890         INIT_LIST_HEAD(&holder->list);
891         holder->disk = disk;
892         holder->refcnt = 1;
893
894         ret = add_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
895         if (ret)
896                 goto out_free;
897
898         ret = add_symlink(bdev->bd_part->holder_dir, &disk_to_dev(disk)->kobj);
899         if (ret)
900                 goto out_del;
901         /*
902          * bdev could be deleted beneath us which would implicitly destroy
903          * the holder directory.  Hold on to it.
904          */
905         kobject_get(bdev->bd_part->holder_dir);
906
907         list_add(&holder->list, &bdev->bd_holder_disks);
908         goto out_unlock;
909
910 out_del:
911         del_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
912 out_free:
913         kfree(holder);
914 out_unlock:
915         mutex_unlock(&bdev->bd_mutex);
916         return ret;
917 }
918 EXPORT_SYMBOL_GPL(bd_link_disk_holder);
919
920 /**
921  * bd_unlink_disk_holder - destroy symlinks created by bd_link_disk_holder()
922  * @bdev: the calimed slave bdev
923  * @disk: the holding disk
924  *
925  * DON'T USE THIS UNLESS YOU'RE ALREADY USING IT.
926  *
927  * CONTEXT:
928  * Might sleep.
929  */
930 void bd_unlink_disk_holder(struct block_device *bdev, struct gendisk *disk)
931 {
932         struct bd_holder_disk *holder;
933
934         mutex_lock(&bdev->bd_mutex);
935
936         holder = bd_find_holder_disk(bdev, disk);
937
938         if (!WARN_ON_ONCE(holder == NULL) && !--holder->refcnt) {
939                 del_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
940                 del_symlink(bdev->bd_part->holder_dir,
941                             &disk_to_dev(disk)->kobj);
942                 kobject_put(bdev->bd_part->holder_dir);
943                 list_del_init(&holder->list);
944                 kfree(holder);
945         }
946
947         mutex_unlock(&bdev->bd_mutex);
948 }
949 EXPORT_SYMBOL_GPL(bd_unlink_disk_holder);
950 #endif
951
952 /**
953  * flush_disk - invalidates all buffer-cache entries on a disk
954  *
955  * @bdev:      struct block device to be flushed
956  * @kill_dirty: flag to guide handling of dirty inodes
957  *
958  * Invalidates all buffer-cache entries on a disk. It should be called
959  * when a disk has been changed -- either by a media change or online
960  * resize.
961  */
962 static void flush_disk(struct block_device *bdev, bool kill_dirty)
963 {
964         if (__invalidate_device(bdev, kill_dirty)) {
965                 char name[BDEVNAME_SIZE] = "";
966
967                 if (bdev->bd_disk)
968                         disk_name(bdev->bd_disk, 0, name);
969                 printk(KERN_WARNING "VFS: busy inodes on changed media or "
970                        "resized disk %s\n", name);
971         }
972
973         if (!bdev->bd_disk)
974                 return;
975         if (disk_part_scan_enabled(bdev->bd_disk))
976                 bdev->bd_invalidated = 1;
977 }
978
979 /**
980  * check_disk_size_change - checks for disk size change and adjusts bdev size.
981  * @disk: struct gendisk to check
982  * @bdev: struct bdev to adjust.
983  *
984  * This routine checks to see if the bdev size does not match the disk size
985  * and adjusts it if it differs.
986  */
987 void check_disk_size_change(struct gendisk *disk, struct block_device *bdev)
988 {
989         loff_t disk_size, bdev_size;
990
991         disk_size = (loff_t)get_capacity(disk) << 9;
992         bdev_size = i_size_read(bdev->bd_inode);
993         if (disk_size != bdev_size) {
994                 char name[BDEVNAME_SIZE];
995
996                 disk_name(disk, 0, name);
997                 printk(KERN_INFO
998                        "%s: detected capacity change from %lld to %lld\n",
999                        name, bdev_size, disk_size);
1000                 i_size_write(bdev->bd_inode, disk_size);
1001                 flush_disk(bdev, false);
1002         }
1003 }
1004 EXPORT_SYMBOL(check_disk_size_change);
1005
1006 /**
1007  * revalidate_disk - wrapper for lower-level driver's revalidate_disk call-back
1008  * @disk: struct gendisk to be revalidated
1009  *
1010  * This routine is a wrapper for lower-level driver's revalidate_disk
1011  * call-backs.  It is used to do common pre and post operations needed
1012  * for all revalidate_disk operations.
1013  */
1014 int revalidate_disk(struct gendisk *disk)
1015 {
1016         struct block_device *bdev;
1017         int ret = 0;
1018
1019         if (disk->fops->revalidate_disk)
1020                 ret = disk->fops->revalidate_disk(disk);
1021
1022         bdev = bdget_disk(disk, 0);
1023         if (!bdev)
1024                 return ret;
1025
1026         mutex_lock(&bdev->bd_mutex);
1027         check_disk_size_change(disk, bdev);
1028         bdev->bd_invalidated = 0;
1029         mutex_unlock(&bdev->bd_mutex);
1030         bdput(bdev);
1031         return ret;
1032 }
1033 EXPORT_SYMBOL(revalidate_disk);
1034
1035 /*
1036  * This routine checks whether a removable media has been changed,
1037  * and invalidates all buffer-cache-entries in that case. This
1038  * is a relatively slow routine, so we have to try to minimize using
1039  * it. Thus it is called only upon a 'mount' or 'open'. This
1040  * is the best way of combining speed and utility, I think.
1041  * People changing diskettes in the middle of an operation deserve
1042  * to lose :-)
1043  */
1044 int check_disk_change(struct block_device *bdev)
1045 {
1046         struct gendisk *disk = bdev->bd_disk;
1047         const struct block_device_operations *bdops = disk->fops;
1048         unsigned int events;
1049
1050         events = disk_clear_events(disk, DISK_EVENT_MEDIA_CHANGE |
1051                                    DISK_EVENT_EJECT_REQUEST);
1052         if (!(events & DISK_EVENT_MEDIA_CHANGE))
1053                 return 0;
1054
1055         flush_disk(bdev, true);
1056         if (bdops->revalidate_disk)
1057                 bdops->revalidate_disk(bdev->bd_disk);
1058         return 1;
1059 }
1060
1061 EXPORT_SYMBOL(check_disk_change);
1062
1063 void bd_set_size(struct block_device *bdev, loff_t size)
1064 {
1065         unsigned bsize = bdev_logical_block_size(bdev);
1066
1067         mutex_lock(&bdev->bd_inode->i_mutex);
1068         i_size_write(bdev->bd_inode, size);
1069         mutex_unlock(&bdev->bd_inode->i_mutex);
1070         while (bsize < PAGE_CACHE_SIZE) {
1071                 if (size & bsize)
1072                         break;
1073                 bsize <<= 1;
1074         }
1075         bdev->bd_block_size = bsize;
1076         bdev->bd_inode->i_blkbits = blksize_bits(bsize);
1077 }
1078 EXPORT_SYMBOL(bd_set_size);
1079
1080 static int __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part);
1081
1082 /*
1083  * bd_mutex locking:
1084  *
1085  *  mutex_lock(part->bd_mutex)
1086  *    mutex_lock_nested(whole->bd_mutex, 1)
1087  */
1088
1089 static int __blkdev_get(struct block_device *bdev, fmode_t mode, int for_part)
1090 {
1091         struct gendisk *disk;
1092         struct module *owner;
1093         int ret;
1094         int partno;
1095         int perm = 0;
1096
1097         if (mode & FMODE_READ)
1098                 perm |= MAY_READ;
1099         if (mode & FMODE_WRITE)
1100                 perm |= MAY_WRITE;
1101         /*
1102          * hooks: /n/, see "layering violations".
1103          */
1104         if (!for_part) {
1105                 ret = devcgroup_inode_permission(bdev->bd_inode, perm);
1106                 if (ret != 0) {
1107                         bdput(bdev);
1108                         return ret;
1109                 }
1110         }
1111
1112  restart:
1113
1114         ret = -ENXIO;
1115         disk = get_gendisk(bdev->bd_dev, &partno);
1116         if (!disk)
1117                 goto out;
1118         owner = disk->fops->owner;
1119
1120         disk_block_events(disk);
1121         mutex_lock_nested(&bdev->bd_mutex, for_part);
1122         if (!bdev->bd_openers) {
1123                 bdev->bd_disk = disk;
1124                 bdev->bd_contains = bdev;
1125                 if (!partno) {
1126                         struct backing_dev_info *bdi;
1127
1128                         ret = -ENXIO;
1129                         bdev->bd_part = disk_get_part(disk, partno);
1130                         if (!bdev->bd_part)
1131                                 goto out_clear;
1132
1133                         ret = 0;
1134                         if (disk->fops->open) {
1135                                 ret = disk->fops->open(bdev, mode);
1136                                 if (ret == -ERESTARTSYS) {
1137                                         /* Lost a race with 'disk' being
1138                                          * deleted, try again.
1139                                          * See md.c
1140                                          */
1141                                         disk_put_part(bdev->bd_part);
1142                                         bdev->bd_part = NULL;
1143                                         bdev->bd_disk = NULL;
1144                                         mutex_unlock(&bdev->bd_mutex);
1145                                         disk_unblock_events(disk);
1146                                         put_disk(disk);
1147                                         module_put(owner);
1148                                         goto restart;
1149                                 }
1150                         }
1151
1152                         if (!ret && !bdev->bd_openers) {
1153                                 bd_set_size(bdev,(loff_t)get_capacity(disk)<<9);
1154                                 bdi = blk_get_backing_dev_info(bdev);
1155                                 if (bdi == NULL)
1156                                         bdi = &default_backing_dev_info;
1157                                 bdev_inode_switch_bdi(bdev->bd_inode, bdi);
1158                         }
1159
1160                         /*
1161                          * If the device is invalidated, rescan partition
1162                          * if open succeeded or failed with -ENOMEDIUM.
1163                          * The latter is necessary to prevent ghost
1164                          * partitions on a removed medium.
1165                          */
1166                         if (bdev->bd_invalidated) {
1167                                 if (!ret)
1168                                         rescan_partitions(disk, bdev);
1169                                 else if (ret == -ENOMEDIUM)
1170                                         invalidate_partitions(disk, bdev);
1171                         }
1172                         if (ret)
1173                                 goto out_clear;
1174                 } else {
1175                         struct block_device *whole;
1176                         whole = bdget_disk(disk, 0);
1177                         ret = -ENOMEM;
1178                         if (!whole)
1179                                 goto out_clear;
1180                         BUG_ON(for_part);
1181                         ret = __blkdev_get(whole, mode, 1);
1182                         if (ret)
1183                                 goto out_clear;
1184                         bdev->bd_contains = whole;
1185                         bdev_inode_switch_bdi(bdev->bd_inode,
1186                                 whole->bd_inode->i_data.backing_dev_info);
1187                         bdev->bd_part = disk_get_part(disk, partno);
1188                         if (!(disk->flags & GENHD_FL_UP) ||
1189                             !bdev->bd_part || !bdev->bd_part->nr_sects) {
1190                                 ret = -ENXIO;
1191                                 goto out_clear;
1192                         }
1193                         bd_set_size(bdev, (loff_t)bdev->bd_part->nr_sects << 9);
1194                 }
1195         } else {
1196                 if (bdev->bd_contains == bdev) {
1197                         ret = 0;
1198                         if (bdev->bd_disk->fops->open)
1199                                 ret = bdev->bd_disk->fops->open(bdev, mode);
1200                         /* the same as first opener case, read comment there */
1201                         if (bdev->bd_invalidated) {
1202                                 if (!ret)
1203                                         rescan_partitions(bdev->bd_disk, bdev);
1204                                 else if (ret == -ENOMEDIUM)
1205                                         invalidate_partitions(bdev->bd_disk, bdev);
1206                         }
1207                         if (ret)
1208                                 goto out_unlock_bdev;
1209                 }
1210                 /* only one opener holds refs to the module and disk */
1211                 put_disk(disk);
1212                 module_put(owner);
1213         }
1214         bdev->bd_openers++;
1215         if (for_part)
1216                 bdev->bd_part_count++;
1217         mutex_unlock(&bdev->bd_mutex);
1218         disk_unblock_events(disk);
1219         return 0;
1220
1221  out_clear:
1222         disk_put_part(bdev->bd_part);
1223         bdev->bd_disk = NULL;
1224         bdev->bd_part = NULL;
1225         bdev_inode_switch_bdi(bdev->bd_inode, &default_backing_dev_info);
1226         if (bdev != bdev->bd_contains)
1227                 __blkdev_put(bdev->bd_contains, mode, 1);
1228         bdev->bd_contains = NULL;
1229  out_unlock_bdev:
1230         mutex_unlock(&bdev->bd_mutex);
1231         disk_unblock_events(disk);
1232         put_disk(disk);
1233         module_put(owner);
1234  out:
1235         bdput(bdev);
1236
1237         return ret;
1238 }
1239
1240 /**
1241  * blkdev_get - open a block device
1242  * @bdev: block_device to open
1243  * @mode: FMODE_* mask
1244  * @holder: exclusive holder identifier
1245  *
1246  * Open @bdev with @mode.  If @mode includes %FMODE_EXCL, @bdev is
1247  * open with exclusive access.  Specifying %FMODE_EXCL with %NULL
1248  * @holder is invalid.  Exclusive opens may nest for the same @holder.
1249  *
1250  * On success, the reference count of @bdev is unchanged.  On failure,
1251  * @bdev is put.
1252  *
1253  * CONTEXT:
1254  * Might sleep.
1255  *
1256  * RETURNS:
1257  * 0 on success, -errno on failure.
1258  */
1259 int blkdev_get(struct block_device *bdev, fmode_t mode, void *holder)
1260 {
1261         struct block_device *whole = NULL;
1262         int res;
1263
1264         WARN_ON_ONCE((mode & FMODE_EXCL) && !holder);
1265
1266         if ((mode & FMODE_EXCL) && holder) {
1267                 whole = bd_start_claiming(bdev, holder);
1268                 if (IS_ERR(whole)) {
1269                         bdput(bdev);
1270                         return PTR_ERR(whole);
1271                 }
1272         }
1273
1274         res = __blkdev_get(bdev, mode, 0);
1275
1276         if (whole) {
1277                 struct gendisk *disk = whole->bd_disk;
1278
1279                 /* finish claiming */
1280                 mutex_lock(&bdev->bd_mutex);
1281                 spin_lock(&bdev_lock);
1282
1283                 if (!res) {
1284                         BUG_ON(!bd_may_claim(bdev, whole, holder));
1285                         /*
1286                          * Note that for a whole device bd_holders
1287                          * will be incremented twice, and bd_holder
1288                          * will be set to bd_may_claim before being
1289                          * set to holder
1290                          */
1291                         whole->bd_holders++;
1292                         whole->bd_holder = bd_may_claim;
1293                         bdev->bd_holders++;
1294                         bdev->bd_holder = holder;
1295                 }
1296
1297                 /* tell others that we're done */
1298                 BUG_ON(whole->bd_claiming != holder);
1299                 whole->bd_claiming = NULL;
1300                 wake_up_bit(&whole->bd_claiming, 0);
1301
1302                 spin_unlock(&bdev_lock);
1303
1304                 /*
1305                  * Block event polling for write claims if requested.  Any
1306                  * write holder makes the write_holder state stick until
1307                  * all are released.  This is good enough and tracking
1308                  * individual writeable reference is too fragile given the
1309                  * way @mode is used in blkdev_get/put().
1310                  */
1311                 if (!res && (mode & FMODE_WRITE) && !bdev->bd_write_holder &&
1312                     (disk->flags & GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE)) {
1313                         bdev->bd_write_holder = true;
1314                         disk_block_events(disk);
1315                 }
1316
1317                 mutex_unlock(&bdev->bd_mutex);
1318                 bdput(whole);
1319         }
1320
1321         return res;
1322 }
1323 EXPORT_SYMBOL(blkdev_get);
1324
1325 /**
1326  * blkdev_get_by_path - open a block device by name
1327  * @path: path to the block device to open
1328  * @mode: FMODE_* mask
1329  * @holder: exclusive holder identifier
1330  *
1331  * Open the blockdevice described by the device file at @path.  @mode
1332  * and @holder are identical to blkdev_get().
1333  *
1334  * On success, the returned block_device has reference count of one.
1335  *
1336  * CONTEXT:
1337  * Might sleep.
1338  *
1339  * RETURNS:
1340  * Pointer to block_device on success, ERR_PTR(-errno) on failure.
1341  */
1342 struct block_device *blkdev_get_by_path(const char *path, fmode_t mode,
1343                                         void *holder)
1344 {
1345         struct block_device *bdev;
1346         int err;
1347
1348         bdev = lookup_bdev(path);
1349         if (IS_ERR(bdev))
1350                 return bdev;
1351
1352         err = blkdev_get(bdev, mode, holder);
1353         if (err)
1354                 return ERR_PTR(err);
1355
1356         if ((mode & FMODE_WRITE) && bdev_read_only(bdev)) {
1357                 blkdev_put(bdev, mode);
1358                 return ERR_PTR(-EACCES);
1359         }
1360
1361         return bdev;
1362 }
1363 EXPORT_SYMBOL(blkdev_get_by_path);
1364
1365 /**
1366  * blkdev_get_by_dev - open a block device by device number
1367  * @dev: device number of block device to open
1368  * @mode: FMODE_* mask
1369  * @holder: exclusive holder identifier
1370  *
1371  * Open the blockdevice described by device number @dev.  @mode and
1372  * @holder are identical to blkdev_get().
1373  *
1374  * Use it ONLY if you really do not have anything better - i.e. when
1375  * you are behind a truly sucky interface and all you are given is a
1376  * device number.  _Never_ to be used for internal purposes.  If you
1377  * ever need it - reconsider your API.
1378  *
1379  * On success, the returned block_device has reference count of one.
1380  *
1381  * CONTEXT:
1382  * Might sleep.
1383  *
1384  * RETURNS:
1385  * Pointer to block_device on success, ERR_PTR(-errno) on failure.
1386  */
1387 struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode, void *holder)
1388 {
1389         struct block_device *bdev;
1390         int err;
1391
1392         bdev = bdget(dev);
1393         if (!bdev)
1394                 return ERR_PTR(-ENOMEM);
1395
1396         err = blkdev_get(bdev, mode, holder);
1397         if (err)
1398                 return ERR_PTR(err);
1399
1400         return bdev;
1401 }
1402 EXPORT_SYMBOL(blkdev_get_by_dev);
1403
1404 static int blkdev_open(struct inode * inode, struct file * filp)
1405 {
1406         struct block_device *bdev;
1407
1408         /*
1409          * Preserve backwards compatibility and allow large file access
1410          * even if userspace doesn't ask for it explicitly. Some mkfs
1411          * binary needs it. We might want to drop this workaround
1412          * during an unstable branch.
1413          */
1414         filp->f_flags |= O_LARGEFILE;
1415
1416         if (filp->f_flags & O_NDELAY)
1417                 filp->f_mode |= FMODE_NDELAY;
1418         if (filp->f_flags & O_EXCL)
1419                 filp->f_mode |= FMODE_EXCL;
1420         if ((filp->f_flags & O_ACCMODE) == 3)
1421                 filp->f_mode |= FMODE_WRITE_IOCTL;
1422
1423         bdev = bd_acquire(inode);
1424         if (bdev == NULL)
1425                 return -ENOMEM;
1426
1427         filp->f_mapping = bdev->bd_inode->i_mapping;
1428
1429         return blkdev_get(bdev, filp->f_mode, filp);
1430 }
1431
1432 static int __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part)
1433 {
1434         int ret = 0;
1435         struct gendisk *disk = bdev->bd_disk;
1436         struct block_device *victim = NULL;
1437
1438         mutex_lock_nested(&bdev->bd_mutex, for_part);
1439         if (for_part)
1440                 bdev->bd_part_count--;
1441
1442         if (!--bdev->bd_openers) {
1443                 WARN_ON_ONCE(bdev->bd_holders);
1444                 sync_blockdev(bdev);
1445                 kill_bdev(bdev);
1446                 /* ->release can cause the old bdi to disappear,
1447                  * so must switch it out first
1448                  */
1449                 bdev_inode_switch_bdi(bdev->bd_inode,
1450                                         &default_backing_dev_info);
1451         }
1452         if (bdev->bd_contains == bdev) {
1453                 if (disk->fops->release)
1454                         ret = disk->fops->release(disk, mode);
1455         }
1456         if (!bdev->bd_openers) {
1457                 struct module *owner = disk->fops->owner;
1458
1459                 disk_put_part(bdev->bd_part);
1460                 bdev->bd_part = NULL;
1461                 bdev->bd_disk = NULL;
1462                 if (bdev != bdev->bd_contains)
1463                         victim = bdev->bd_contains;
1464                 bdev->bd_contains = NULL;
1465
1466                 put_disk(disk);
1467                 module_put(owner);
1468         }
1469         mutex_unlock(&bdev->bd_mutex);
1470         bdput(bdev);
1471         if (victim)
1472                 __blkdev_put(victim, mode, 1);
1473         return ret;
1474 }
1475
1476 int blkdev_put(struct block_device *bdev, fmode_t mode)
1477 {
1478         mutex_lock(&bdev->bd_mutex);
1479
1480         if (mode & FMODE_EXCL) {
1481                 bool bdev_free;
1482
1483                 /*
1484                  * Release a claim on the device.  The holder fields
1485                  * are protected with bdev_lock.  bd_mutex is to
1486                  * synchronize disk_holder unlinking.
1487                  */
1488                 spin_lock(&bdev_lock);
1489
1490                 WARN_ON_ONCE(--bdev->bd_holders < 0);
1491                 WARN_ON_ONCE(--bdev->bd_contains->bd_holders < 0);
1492
1493                 /* bd_contains might point to self, check in a separate step */
1494                 if ((bdev_free = !bdev->bd_holders))
1495                         bdev->bd_holder = NULL;
1496                 if (!bdev->bd_contains->bd_holders)
1497                         bdev->bd_contains->bd_holder = NULL;
1498
1499                 spin_unlock(&bdev_lock);
1500
1501                 /*
1502                  * If this was the last claim, remove holder link and
1503                  * unblock evpoll if it was a write holder.
1504                  */
1505                 if (bdev_free && bdev->bd_write_holder) {
1506                         disk_unblock_events(bdev->bd_disk);
1507                         bdev->bd_write_holder = false;
1508                 }
1509         }
1510
1511         /*
1512          * Trigger event checking and tell drivers to flush MEDIA_CHANGE
1513          * event.  This is to ensure detection of media removal commanded
1514          * from userland - e.g. eject(1).
1515          */
1516         disk_flush_events(bdev->bd_disk, DISK_EVENT_MEDIA_CHANGE);
1517
1518         mutex_unlock(&bdev->bd_mutex);
1519
1520         return __blkdev_put(bdev, mode, 0);
1521 }
1522 EXPORT_SYMBOL(blkdev_put);
1523
1524 static int blkdev_close(struct inode * inode, struct file * filp)
1525 {
1526         struct block_device *bdev = I_BDEV(filp->f_mapping->host);
1527
1528         return blkdev_put(bdev, filp->f_mode);
1529 }
1530
1531 static long block_ioctl(struct file *file, unsigned cmd, unsigned long arg)
1532 {
1533         struct block_device *bdev = I_BDEV(file->f_mapping->host);
1534         fmode_t mode = file->f_mode;
1535
1536         /*
1537          * O_NDELAY can be altered using fcntl(.., F_SETFL, ..), so we have
1538          * to updated it before every ioctl.
1539          */
1540         if (file->f_flags & O_NDELAY)
1541                 mode |= FMODE_NDELAY;
1542         else
1543                 mode &= ~FMODE_NDELAY;
1544
1545         return blkdev_ioctl(bdev, mode, cmd, arg);
1546 }
1547
1548 /*
1549  * Write data to the block device.  Only intended for the block device itself
1550  * and the raw driver which basically is a fake block device.
1551  *
1552  * Does not take i_mutex for the write and thus is not for general purpose
1553  * use.
1554  */
1555 ssize_t blkdev_aio_write(struct kiocb *iocb, const struct iovec *iov,
1556                          unsigned long nr_segs, loff_t pos)
1557 {
1558         struct file *file = iocb->ki_filp;
1559         ssize_t ret;
1560
1561         BUG_ON(iocb->ki_pos != pos);
1562
1563         ret = __generic_file_aio_write(iocb, iov, nr_segs, &iocb->ki_pos);
1564         if (ret > 0 || ret == -EIOCBQUEUED) {
1565                 ssize_t err;
1566
1567                 err = generic_write_sync(file, pos, ret);
1568                 if (err < 0 && ret > 0)
1569                         ret = err;
1570         }
1571         return ret;
1572 }
1573 EXPORT_SYMBOL_GPL(blkdev_aio_write);
1574
1575 /*
1576  * Try to release a page associated with block device when the system
1577  * is under memory pressure.
1578  */
1579 static int blkdev_releasepage(struct page *page, gfp_t wait)
1580 {
1581         struct super_block *super = BDEV_I(page->mapping->host)->bdev.bd_super;
1582
1583         if (super && super->s_op->bdev_try_to_free_page)
1584                 return super->s_op->bdev_try_to_free_page(super, page, wait);
1585
1586         return try_to_free_buffers(page);
1587 }
1588
1589 static const struct address_space_operations def_blk_aops = {
1590         .readpage       = blkdev_readpage,
1591         .writepage      = blkdev_writepage,
1592         .write_begin    = blkdev_write_begin,
1593         .write_end      = blkdev_write_end,
1594         .writepages     = generic_writepages,
1595         .releasepage    = blkdev_releasepage,
1596         .direct_IO      = blkdev_direct_IO,
1597 };
1598
1599 const struct file_operations def_blk_fops = {
1600         .open           = blkdev_open,
1601         .release        = blkdev_close,
1602         .llseek         = block_llseek,
1603         .read           = do_sync_read,
1604         .write          = do_sync_write,
1605         .aio_read       = generic_file_aio_read,
1606         .aio_write      = blkdev_aio_write,
1607         .mmap           = generic_file_mmap,
1608         .fsync          = blkdev_fsync,
1609         .unlocked_ioctl = block_ioctl,
1610 #ifdef CONFIG_COMPAT
1611         .compat_ioctl   = compat_blkdev_ioctl,
1612 #endif
1613         .splice_read    = generic_file_splice_read,
1614         .splice_write   = generic_file_splice_write,
1615 };
1616
1617 int ioctl_by_bdev(struct block_device *bdev, unsigned cmd, unsigned long arg)
1618 {
1619         int res;
1620         mm_segment_t old_fs = get_fs();
1621         set_fs(KERNEL_DS);
1622         res = blkdev_ioctl(bdev, 0, cmd, arg);
1623         set_fs(old_fs);
1624         return res;
1625 }
1626
1627 EXPORT_SYMBOL(ioctl_by_bdev);
1628
1629 /**
1630  * lookup_bdev  - lookup a struct block_device by name
1631  * @pathname:   special file representing the block device
1632  *
1633  * Get a reference to the blockdevice at @pathname in the current
1634  * namespace if possible and return it.  Return ERR_PTR(error)
1635  * otherwise.
1636  */
1637 struct block_device *lookup_bdev(const char *pathname)
1638 {
1639         struct block_device *bdev;
1640         struct inode *inode;
1641         struct path path;
1642         int error;
1643
1644         if (!pathname || !*pathname)
1645                 return ERR_PTR(-EINVAL);
1646
1647         error = kern_path(pathname, LOOKUP_FOLLOW, &path);
1648         if (error)
1649                 return ERR_PTR(error);
1650
1651         inode = path.dentry->d_inode;
1652         error = -ENOTBLK;
1653         if (!S_ISBLK(inode->i_mode))
1654                 goto fail;
1655         error = -EACCES;
1656         if (path.mnt->mnt_flags & MNT_NODEV)
1657                 goto fail;
1658         error = -ENOMEM;
1659         bdev = bd_acquire(inode);
1660         if (!bdev)
1661                 goto fail;
1662 out:
1663         path_put(&path);
1664         return bdev;
1665 fail:
1666         bdev = ERR_PTR(error);
1667         goto out;
1668 }
1669 EXPORT_SYMBOL(lookup_bdev);
1670
1671 int __invalidate_device(struct block_device *bdev, bool kill_dirty)
1672 {
1673         struct super_block *sb = get_super(bdev);
1674         int res = 0;
1675
1676         if (sb) {
1677                 /*
1678                  * no need to lock the super, get_super holds the
1679                  * read mutex so the filesystem cannot go away
1680                  * under us (->put_super runs with the write lock
1681                  * hold).
1682                  */
1683                 shrink_dcache_sb(sb);
1684                 res = invalidate_inodes(sb, kill_dirty);
1685                 drop_super(sb);
1686         }
1687         invalidate_bdev(bdev);
1688         return res;
1689 }
1690 EXPORT_SYMBOL(__invalidate_device);