nbd: fsync and kill block device on shutdown
[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         bdev->bd_inode->i_size = size;
1068         while (bsize < PAGE_CACHE_SIZE) {
1069                 if (size & bsize)
1070                         break;
1071                 bsize <<= 1;
1072         }
1073         bdev->bd_block_size = bsize;
1074         bdev->bd_inode->i_blkbits = blksize_bits(bsize);
1075 }
1076 EXPORT_SYMBOL(bd_set_size);
1077
1078 static int __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part);
1079
1080 /*
1081  * bd_mutex locking:
1082  *
1083  *  mutex_lock(part->bd_mutex)
1084  *    mutex_lock_nested(whole->bd_mutex, 1)
1085  */
1086
1087 static int __blkdev_get(struct block_device *bdev, fmode_t mode, int for_part)
1088 {
1089         struct gendisk *disk;
1090         struct module *owner;
1091         int ret;
1092         int partno;
1093         int perm = 0;
1094
1095         if (mode & FMODE_READ)
1096                 perm |= MAY_READ;
1097         if (mode & FMODE_WRITE)
1098                 perm |= MAY_WRITE;
1099         /*
1100          * hooks: /n/, see "layering violations".
1101          */
1102         if (!for_part) {
1103                 ret = devcgroup_inode_permission(bdev->bd_inode, perm);
1104                 if (ret != 0) {
1105                         bdput(bdev);
1106                         return ret;
1107                 }
1108         }
1109
1110  restart:
1111
1112         ret = -ENXIO;
1113         disk = get_gendisk(bdev->bd_dev, &partno);
1114         if (!disk)
1115                 goto out;
1116         owner = disk->fops->owner;
1117
1118         disk_block_events(disk);
1119         mutex_lock_nested(&bdev->bd_mutex, for_part);
1120         if (!bdev->bd_openers) {
1121                 bdev->bd_disk = disk;
1122                 bdev->bd_contains = bdev;
1123                 if (!partno) {
1124                         struct backing_dev_info *bdi;
1125
1126                         ret = -ENXIO;
1127                         bdev->bd_part = disk_get_part(disk, partno);
1128                         if (!bdev->bd_part)
1129                                 goto out_clear;
1130
1131                         ret = 0;
1132                         if (disk->fops->open) {
1133                                 ret = disk->fops->open(bdev, mode);
1134                                 if (ret == -ERESTARTSYS) {
1135                                         /* Lost a race with 'disk' being
1136                                          * deleted, try again.
1137                                          * See md.c
1138                                          */
1139                                         disk_put_part(bdev->bd_part);
1140                                         bdev->bd_part = NULL;
1141                                         bdev->bd_disk = NULL;
1142                                         mutex_unlock(&bdev->bd_mutex);
1143                                         disk_unblock_events(disk);
1144                                         put_disk(disk);
1145                                         module_put(owner);
1146                                         goto restart;
1147                                 }
1148                         }
1149
1150                         if (!ret && !bdev->bd_openers) {
1151                                 bd_set_size(bdev,(loff_t)get_capacity(disk)<<9);
1152                                 bdi = blk_get_backing_dev_info(bdev);
1153                                 if (bdi == NULL)
1154                                         bdi = &default_backing_dev_info;
1155                                 bdev_inode_switch_bdi(bdev->bd_inode, bdi);
1156                         }
1157
1158                         /*
1159                          * If the device is invalidated, rescan partition
1160                          * if open succeeded or failed with -ENOMEDIUM.
1161                          * The latter is necessary to prevent ghost
1162                          * partitions on a removed medium.
1163                          */
1164                         if (bdev->bd_invalidated) {
1165                                 if (!ret)
1166                                         rescan_partitions(disk, bdev);
1167                                 else if (ret == -ENOMEDIUM)
1168                                         invalidate_partitions(disk, bdev);
1169                         }
1170                         if (ret)
1171                                 goto out_clear;
1172                 } else {
1173                         struct block_device *whole;
1174                         whole = bdget_disk(disk, 0);
1175                         ret = -ENOMEM;
1176                         if (!whole)
1177                                 goto out_clear;
1178                         BUG_ON(for_part);
1179                         ret = __blkdev_get(whole, mode, 1);
1180                         if (ret)
1181                                 goto out_clear;
1182                         bdev->bd_contains = whole;
1183                         bdev_inode_switch_bdi(bdev->bd_inode,
1184                                 whole->bd_inode->i_data.backing_dev_info);
1185                         bdev->bd_part = disk_get_part(disk, partno);
1186                         if (!(disk->flags & GENHD_FL_UP) ||
1187                             !bdev->bd_part || !bdev->bd_part->nr_sects) {
1188                                 ret = -ENXIO;
1189                                 goto out_clear;
1190                         }
1191                         bd_set_size(bdev, (loff_t)bdev->bd_part->nr_sects << 9);
1192                 }
1193         } else {
1194                 if (bdev->bd_contains == bdev) {
1195                         ret = 0;
1196                         if (bdev->bd_disk->fops->open)
1197                                 ret = bdev->bd_disk->fops->open(bdev, mode);
1198                         /* the same as first opener case, read comment there */
1199                         if (bdev->bd_invalidated) {
1200                                 if (!ret)
1201                                         rescan_partitions(bdev->bd_disk, bdev);
1202                                 else if (ret == -ENOMEDIUM)
1203                                         invalidate_partitions(bdev->bd_disk, bdev);
1204                         }
1205                         if (ret)
1206                                 goto out_unlock_bdev;
1207                 }
1208                 /* only one opener holds refs to the module and disk */
1209                 put_disk(disk);
1210                 module_put(owner);
1211         }
1212         bdev->bd_openers++;
1213         if (for_part)
1214                 bdev->bd_part_count++;
1215         mutex_unlock(&bdev->bd_mutex);
1216         disk_unblock_events(disk);
1217         return 0;
1218
1219  out_clear:
1220         disk_put_part(bdev->bd_part);
1221         bdev->bd_disk = NULL;
1222         bdev->bd_part = NULL;
1223         bdev_inode_switch_bdi(bdev->bd_inode, &default_backing_dev_info);
1224         if (bdev != bdev->bd_contains)
1225                 __blkdev_put(bdev->bd_contains, mode, 1);
1226         bdev->bd_contains = NULL;
1227  out_unlock_bdev:
1228         mutex_unlock(&bdev->bd_mutex);
1229         disk_unblock_events(disk);
1230         put_disk(disk);
1231         module_put(owner);
1232  out:
1233         bdput(bdev);
1234
1235         return ret;
1236 }
1237
1238 /**
1239  * blkdev_get - open a block device
1240  * @bdev: block_device to open
1241  * @mode: FMODE_* mask
1242  * @holder: exclusive holder identifier
1243  *
1244  * Open @bdev with @mode.  If @mode includes %FMODE_EXCL, @bdev is
1245  * open with exclusive access.  Specifying %FMODE_EXCL with %NULL
1246  * @holder is invalid.  Exclusive opens may nest for the same @holder.
1247  *
1248  * On success, the reference count of @bdev is unchanged.  On failure,
1249  * @bdev is put.
1250  *
1251  * CONTEXT:
1252  * Might sleep.
1253  *
1254  * RETURNS:
1255  * 0 on success, -errno on failure.
1256  */
1257 int blkdev_get(struct block_device *bdev, fmode_t mode, void *holder)
1258 {
1259         struct block_device *whole = NULL;
1260         int res;
1261
1262         WARN_ON_ONCE((mode & FMODE_EXCL) && !holder);
1263
1264         if ((mode & FMODE_EXCL) && holder) {
1265                 whole = bd_start_claiming(bdev, holder);
1266                 if (IS_ERR(whole)) {
1267                         bdput(bdev);
1268                         return PTR_ERR(whole);
1269                 }
1270         }
1271
1272         res = __blkdev_get(bdev, mode, 0);
1273
1274         if (whole) {
1275                 struct gendisk *disk = whole->bd_disk;
1276
1277                 /* finish claiming */
1278                 mutex_lock(&bdev->bd_mutex);
1279                 spin_lock(&bdev_lock);
1280
1281                 if (!res) {
1282                         BUG_ON(!bd_may_claim(bdev, whole, holder));
1283                         /*
1284                          * Note that for a whole device bd_holders
1285                          * will be incremented twice, and bd_holder
1286                          * will be set to bd_may_claim before being
1287                          * set to holder
1288                          */
1289                         whole->bd_holders++;
1290                         whole->bd_holder = bd_may_claim;
1291                         bdev->bd_holders++;
1292                         bdev->bd_holder = holder;
1293                 }
1294
1295                 /* tell others that we're done */
1296                 BUG_ON(whole->bd_claiming != holder);
1297                 whole->bd_claiming = NULL;
1298                 wake_up_bit(&whole->bd_claiming, 0);
1299
1300                 spin_unlock(&bdev_lock);
1301
1302                 /*
1303                  * Block event polling for write claims if requested.  Any
1304                  * write holder makes the write_holder state stick until
1305                  * all are released.  This is good enough and tracking
1306                  * individual writeable reference is too fragile given the
1307                  * way @mode is used in blkdev_get/put().
1308                  */
1309                 if (!res && (mode & FMODE_WRITE) && !bdev->bd_write_holder &&
1310                     (disk->flags & GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE)) {
1311                         bdev->bd_write_holder = true;
1312                         disk_block_events(disk);
1313                 }
1314
1315                 mutex_unlock(&bdev->bd_mutex);
1316                 bdput(whole);
1317         }
1318
1319         return res;
1320 }
1321 EXPORT_SYMBOL(blkdev_get);
1322
1323 /**
1324  * blkdev_get_by_path - open a block device by name
1325  * @path: path to the block device to open
1326  * @mode: FMODE_* mask
1327  * @holder: exclusive holder identifier
1328  *
1329  * Open the blockdevice described by the device file at @path.  @mode
1330  * and @holder are identical to blkdev_get().
1331  *
1332  * On success, the returned block_device has reference count of one.
1333  *
1334  * CONTEXT:
1335  * Might sleep.
1336  *
1337  * RETURNS:
1338  * Pointer to block_device on success, ERR_PTR(-errno) on failure.
1339  */
1340 struct block_device *blkdev_get_by_path(const char *path, fmode_t mode,
1341                                         void *holder)
1342 {
1343         struct block_device *bdev;
1344         int err;
1345
1346         bdev = lookup_bdev(path);
1347         if (IS_ERR(bdev))
1348                 return bdev;
1349
1350         err = blkdev_get(bdev, mode, holder);
1351         if (err)
1352                 return ERR_PTR(err);
1353
1354         if ((mode & FMODE_WRITE) && bdev_read_only(bdev)) {
1355                 blkdev_put(bdev, mode);
1356                 return ERR_PTR(-EACCES);
1357         }
1358
1359         return bdev;
1360 }
1361 EXPORT_SYMBOL(blkdev_get_by_path);
1362
1363 /**
1364  * blkdev_get_by_dev - open a block device by device number
1365  * @dev: device number of block device to open
1366  * @mode: FMODE_* mask
1367  * @holder: exclusive holder identifier
1368  *
1369  * Open the blockdevice described by device number @dev.  @mode and
1370  * @holder are identical to blkdev_get().
1371  *
1372  * Use it ONLY if you really do not have anything better - i.e. when
1373  * you are behind a truly sucky interface and all you are given is a
1374  * device number.  _Never_ to be used for internal purposes.  If you
1375  * ever need it - reconsider your API.
1376  *
1377  * On success, the returned block_device has reference count of one.
1378  *
1379  * CONTEXT:
1380  * Might sleep.
1381  *
1382  * RETURNS:
1383  * Pointer to block_device on success, ERR_PTR(-errno) on failure.
1384  */
1385 struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode, void *holder)
1386 {
1387         struct block_device *bdev;
1388         int err;
1389
1390         bdev = bdget(dev);
1391         if (!bdev)
1392                 return ERR_PTR(-ENOMEM);
1393
1394         err = blkdev_get(bdev, mode, holder);
1395         if (err)
1396                 return ERR_PTR(err);
1397
1398         return bdev;
1399 }
1400 EXPORT_SYMBOL(blkdev_get_by_dev);
1401
1402 static int blkdev_open(struct inode * inode, struct file * filp)
1403 {
1404         struct block_device *bdev;
1405
1406         /*
1407          * Preserve backwards compatibility and allow large file access
1408          * even if userspace doesn't ask for it explicitly. Some mkfs
1409          * binary needs it. We might want to drop this workaround
1410          * during an unstable branch.
1411          */
1412         filp->f_flags |= O_LARGEFILE;
1413
1414         if (filp->f_flags & O_NDELAY)
1415                 filp->f_mode |= FMODE_NDELAY;
1416         if (filp->f_flags & O_EXCL)
1417                 filp->f_mode |= FMODE_EXCL;
1418         if ((filp->f_flags & O_ACCMODE) == 3)
1419                 filp->f_mode |= FMODE_WRITE_IOCTL;
1420
1421         bdev = bd_acquire(inode);
1422         if (bdev == NULL)
1423                 return -ENOMEM;
1424
1425         filp->f_mapping = bdev->bd_inode->i_mapping;
1426
1427         return blkdev_get(bdev, filp->f_mode, filp);
1428 }
1429
1430 static int __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part)
1431 {
1432         int ret = 0;
1433         struct gendisk *disk = bdev->bd_disk;
1434         struct block_device *victim = NULL;
1435
1436         mutex_lock_nested(&bdev->bd_mutex, for_part);
1437         if (for_part)
1438                 bdev->bd_part_count--;
1439
1440         if (!--bdev->bd_openers) {
1441                 WARN_ON_ONCE(bdev->bd_holders);
1442                 sync_blockdev(bdev);
1443                 kill_bdev(bdev);
1444                 /* ->release can cause the old bdi to disappear,
1445                  * so must switch it out first
1446                  */
1447                 bdev_inode_switch_bdi(bdev->bd_inode,
1448                                         &default_backing_dev_info);
1449         }
1450         if (bdev->bd_contains == bdev) {
1451                 if (disk->fops->release)
1452                         ret = disk->fops->release(disk, mode);
1453         }
1454         if (!bdev->bd_openers) {
1455                 struct module *owner = disk->fops->owner;
1456
1457                 disk_put_part(bdev->bd_part);
1458                 bdev->bd_part = NULL;
1459                 bdev->bd_disk = NULL;
1460                 if (bdev != bdev->bd_contains)
1461                         victim = bdev->bd_contains;
1462                 bdev->bd_contains = NULL;
1463
1464                 put_disk(disk);
1465                 module_put(owner);
1466         }
1467         mutex_unlock(&bdev->bd_mutex);
1468         bdput(bdev);
1469         if (victim)
1470                 __blkdev_put(victim, mode, 1);
1471         return ret;
1472 }
1473
1474 int blkdev_put(struct block_device *bdev, fmode_t mode)
1475 {
1476         mutex_lock(&bdev->bd_mutex);
1477
1478         if (mode & FMODE_EXCL) {
1479                 bool bdev_free;
1480
1481                 /*
1482                  * Release a claim on the device.  The holder fields
1483                  * are protected with bdev_lock.  bd_mutex is to
1484                  * synchronize disk_holder unlinking.
1485                  */
1486                 spin_lock(&bdev_lock);
1487
1488                 WARN_ON_ONCE(--bdev->bd_holders < 0);
1489                 WARN_ON_ONCE(--bdev->bd_contains->bd_holders < 0);
1490
1491                 /* bd_contains might point to self, check in a separate step */
1492                 if ((bdev_free = !bdev->bd_holders))
1493                         bdev->bd_holder = NULL;
1494                 if (!bdev->bd_contains->bd_holders)
1495                         bdev->bd_contains->bd_holder = NULL;
1496
1497                 spin_unlock(&bdev_lock);
1498
1499                 /*
1500                  * If this was the last claim, remove holder link and
1501                  * unblock evpoll if it was a write holder.
1502                  */
1503                 if (bdev_free && bdev->bd_write_holder) {
1504                         disk_unblock_events(bdev->bd_disk);
1505                         bdev->bd_write_holder = false;
1506                 }
1507         }
1508
1509         /*
1510          * Trigger event checking and tell drivers to flush MEDIA_CHANGE
1511          * event.  This is to ensure detection of media removal commanded
1512          * from userland - e.g. eject(1).
1513          */
1514         disk_flush_events(bdev->bd_disk, DISK_EVENT_MEDIA_CHANGE);
1515
1516         mutex_unlock(&bdev->bd_mutex);
1517
1518         return __blkdev_put(bdev, mode, 0);
1519 }
1520 EXPORT_SYMBOL(blkdev_put);
1521
1522 static int blkdev_close(struct inode * inode, struct file * filp)
1523 {
1524         struct block_device *bdev = I_BDEV(filp->f_mapping->host);
1525
1526         return blkdev_put(bdev, filp->f_mode);
1527 }
1528
1529 static long block_ioctl(struct file *file, unsigned cmd, unsigned long arg)
1530 {
1531         struct block_device *bdev = I_BDEV(file->f_mapping->host);
1532         fmode_t mode = file->f_mode;
1533
1534         /*
1535          * O_NDELAY can be altered using fcntl(.., F_SETFL, ..), so we have
1536          * to updated it before every ioctl.
1537          */
1538         if (file->f_flags & O_NDELAY)
1539                 mode |= FMODE_NDELAY;
1540         else
1541                 mode &= ~FMODE_NDELAY;
1542
1543         return blkdev_ioctl(bdev, mode, cmd, arg);
1544 }
1545
1546 /*
1547  * Write data to the block device.  Only intended for the block device itself
1548  * and the raw driver which basically is a fake block device.
1549  *
1550  * Does not take i_mutex for the write and thus is not for general purpose
1551  * use.
1552  */
1553 ssize_t blkdev_aio_write(struct kiocb *iocb, const struct iovec *iov,
1554                          unsigned long nr_segs, loff_t pos)
1555 {
1556         struct file *file = iocb->ki_filp;
1557         ssize_t ret;
1558
1559         BUG_ON(iocb->ki_pos != pos);
1560
1561         ret = __generic_file_aio_write(iocb, iov, nr_segs, &iocb->ki_pos);
1562         if (ret > 0 || ret == -EIOCBQUEUED) {
1563                 ssize_t err;
1564
1565                 err = generic_write_sync(file, pos, ret);
1566                 if (err < 0 && ret > 0)
1567                         ret = err;
1568         }
1569         return ret;
1570 }
1571 EXPORT_SYMBOL_GPL(blkdev_aio_write);
1572
1573 /*
1574  * Try to release a page associated with block device when the system
1575  * is under memory pressure.
1576  */
1577 static int blkdev_releasepage(struct page *page, gfp_t wait)
1578 {
1579         struct super_block *super = BDEV_I(page->mapping->host)->bdev.bd_super;
1580
1581         if (super && super->s_op->bdev_try_to_free_page)
1582                 return super->s_op->bdev_try_to_free_page(super, page, wait);
1583
1584         return try_to_free_buffers(page);
1585 }
1586
1587 static const struct address_space_operations def_blk_aops = {
1588         .readpage       = blkdev_readpage,
1589         .writepage      = blkdev_writepage,
1590         .write_begin    = blkdev_write_begin,
1591         .write_end      = blkdev_write_end,
1592         .writepages     = generic_writepages,
1593         .releasepage    = blkdev_releasepage,
1594         .direct_IO      = blkdev_direct_IO,
1595 };
1596
1597 const struct file_operations def_blk_fops = {
1598         .open           = blkdev_open,
1599         .release        = blkdev_close,
1600         .llseek         = block_llseek,
1601         .read           = do_sync_read,
1602         .write          = do_sync_write,
1603         .aio_read       = generic_file_aio_read,
1604         .aio_write      = blkdev_aio_write,
1605         .mmap           = generic_file_mmap,
1606         .fsync          = blkdev_fsync,
1607         .unlocked_ioctl = block_ioctl,
1608 #ifdef CONFIG_COMPAT
1609         .compat_ioctl   = compat_blkdev_ioctl,
1610 #endif
1611         .splice_read    = generic_file_splice_read,
1612         .splice_write   = generic_file_splice_write,
1613 };
1614
1615 int ioctl_by_bdev(struct block_device *bdev, unsigned cmd, unsigned long arg)
1616 {
1617         int res;
1618         mm_segment_t old_fs = get_fs();
1619         set_fs(KERNEL_DS);
1620         res = blkdev_ioctl(bdev, 0, cmd, arg);
1621         set_fs(old_fs);
1622         return res;
1623 }
1624
1625 EXPORT_SYMBOL(ioctl_by_bdev);
1626
1627 /**
1628  * lookup_bdev  - lookup a struct block_device by name
1629  * @pathname:   special file representing the block device
1630  *
1631  * Get a reference to the blockdevice at @pathname in the current
1632  * namespace if possible and return it.  Return ERR_PTR(error)
1633  * otherwise.
1634  */
1635 struct block_device *lookup_bdev(const char *pathname)
1636 {
1637         struct block_device *bdev;
1638         struct inode *inode;
1639         struct path path;
1640         int error;
1641
1642         if (!pathname || !*pathname)
1643                 return ERR_PTR(-EINVAL);
1644
1645         error = kern_path(pathname, LOOKUP_FOLLOW, &path);
1646         if (error)
1647                 return ERR_PTR(error);
1648
1649         inode = path.dentry->d_inode;
1650         error = -ENOTBLK;
1651         if (!S_ISBLK(inode->i_mode))
1652                 goto fail;
1653         error = -EACCES;
1654         if (path.mnt->mnt_flags & MNT_NODEV)
1655                 goto fail;
1656         error = -ENOMEM;
1657         bdev = bd_acquire(inode);
1658         if (!bdev)
1659                 goto fail;
1660 out:
1661         path_put(&path);
1662         return bdev;
1663 fail:
1664         bdev = ERR_PTR(error);
1665         goto out;
1666 }
1667 EXPORT_SYMBOL(lookup_bdev);
1668
1669 int __invalidate_device(struct block_device *bdev, bool kill_dirty)
1670 {
1671         struct super_block *sb = get_super(bdev);
1672         int res = 0;
1673
1674         if (sb) {
1675                 /*
1676                  * no need to lock the super, get_super holds the
1677                  * read mutex so the filesystem cannot go away
1678                  * under us (->put_super runs with the write lock
1679                  * hold).
1680                  */
1681                 shrink_dcache_sb(sb);
1682                 res = invalidate_inodes(sb, kill_dirty);
1683                 drop_super(sb);
1684         }
1685         invalidate_bdev(bdev);
1686         return res;
1687 }
1688 EXPORT_SYMBOL(__invalidate_device);