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