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