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