io_uring: fix manual setup of iov_iter for fixed buffers
[linux-2.6-block.git] / fs / block_dev.c
CommitLineData
457c8996 1// SPDX-License-Identifier: GPL-2.0-only
1da177e4
LT
2/*
3 * linux/fs/block_dev.c
4 *
5 * Copyright (C) 1991, 1992 Linus Torvalds
6 * Copyright (C) 2001 Andrea Arcangeli <andrea@suse.de> SuSE
7 */
8
1da177e4
LT
9#include <linux/init.h>
10#include <linux/mm.h>
11#include <linux/fcntl.h>
12#include <linux/slab.h>
13#include <linux/kmod.h>
14#include <linux/major.h>
7db9cfd3 15#include <linux/device_cgroup.h>
1da177e4
LT
16#include <linux/highmem.h>
17#include <linux/blkdev.h>
66114cad 18#include <linux/backing-dev.h>
1da177e4
LT
19#include <linux/module.h>
20#include <linux/blkpg.h>
b502bd11 21#include <linux/magic.h>
b0686260 22#include <linux/dax.h>
1da177e4 23#include <linux/buffer_head.h>
ff01bb48 24#include <linux/swap.h>
585d3bc0 25#include <linux/pagevec.h>
811d736f 26#include <linux/writeback.h>
1da177e4
LT
27#include <linux/mpage.h>
28#include <linux/mount.h>
9030d16e 29#include <linux/pseudo_fs.h>
1da177e4
LT
30#include <linux/uio.h>
31#include <linux/namei.h>
1368c4f2 32#include <linux/log2.h>
ff01bb48 33#include <linux/cleancache.h>
189ce2b9 34#include <linux/task_io_accounting_ops.h>
25f4c414 35#include <linux/falloc.h>
7c0f6ba6 36#include <linux/uaccess.h>
07f3f05c 37#include "internal.h"
1da177e4
LT
38
39struct bdev_inode {
40 struct block_device bdev;
41 struct inode vfs_inode;
42};
43
4c54ac62
AB
44static const struct address_space_operations def_blk_aops;
45
1da177e4
LT
46static inline struct bdev_inode *BDEV_I(struct inode *inode)
47{
48 return container_of(inode, struct bdev_inode, vfs_inode);
49}
50
ff5053f6 51struct block_device *I_BDEV(struct inode *inode)
1da177e4
LT
52{
53 return &BDEV_I(inode)->bdev;
54}
1da177e4
LT
55EXPORT_SYMBOL(I_BDEV);
56
dbd3ca50 57static void bdev_write_inode(struct block_device *bdev)
564f00f6 58{
dbd3ca50
VG
59 struct inode *inode = bdev->bd_inode;
60 int ret;
61
564f00f6
CH
62 spin_lock(&inode->i_lock);
63 while (inode->i_state & I_DIRTY) {
64 spin_unlock(&inode->i_lock);
dbd3ca50
VG
65 ret = write_inode_now(inode, true);
66 if (ret) {
67 char name[BDEVNAME_SIZE];
68 pr_warn_ratelimited("VFS: Dirty inode writeback failed "
69 "for block device %s (err=%d).\n",
70 bdevname(bdev, name), ret);
71 }
564f00f6
CH
72 spin_lock(&inode->i_lock);
73 }
74 spin_unlock(&inode->i_lock);
75}
76
f9a14399 77/* Kill _all_ buffers and pagecache , dirty or not.. */
ff01bb48 78void kill_bdev(struct block_device *bdev)
1da177e4 79{
ff01bb48
AV
80 struct address_space *mapping = bdev->bd_inode->i_mapping;
81
f9fe48be 82 if (mapping->nrpages == 0 && mapping->nrexceptional == 0)
f9a14399 83 return;
ff01bb48 84
f9a14399 85 invalidate_bh_lrus();
ff01bb48 86 truncate_inode_pages(mapping, 0);
1da177e4 87}
ff01bb48
AV
88EXPORT_SYMBOL(kill_bdev);
89
90/* Invalidate clean unused buffers and pagecache. */
91void invalidate_bdev(struct block_device *bdev)
92{
93 struct address_space *mapping = bdev->bd_inode->i_mapping;
94
a5f6a6a9
AR
95 if (mapping->nrpages) {
96 invalidate_bh_lrus();
97 lru_add_drain_all(); /* make sure all lru add caches are flushed */
98 invalidate_mapping_pages(mapping, 0, -1);
99 }
ff01bb48
AV
100 /* 99% of the time, we don't need to flush the cleancache on the bdev.
101 * But, for the strange corners, lets be cautious
102 */
3167760f 103 cleancache_invalidate_inode(mapping);
ff01bb48
AV
104}
105EXPORT_SYMBOL(invalidate_bdev);
1da177e4 106
04906b2f
JK
107static void set_init_blocksize(struct block_device *bdev)
108{
109 unsigned bsize = bdev_logical_block_size(bdev);
110 loff_t size = i_size_read(bdev->bd_inode);
111
112 while (bsize < PAGE_SIZE) {
113 if (size & bsize)
114 break;
115 bsize <<= 1;
116 }
117 bdev->bd_block_size = bsize;
118 bdev->bd_inode->i_blkbits = blksize_bits(bsize);
119}
120
1da177e4
LT
121int set_blocksize(struct block_device *bdev, int size)
122{
123 /* Size must be a power of two, and between 512 and PAGE_SIZE */
1368c4f2 124 if (size > PAGE_SIZE || size < 512 || !is_power_of_2(size))
1da177e4
LT
125 return -EINVAL;
126
127 /* Size cannot be smaller than the size supported by the device */
e1defc4f 128 if (size < bdev_logical_block_size(bdev))
1da177e4
LT
129 return -EINVAL;
130
131 /* Don't change the size if it is same as current */
132 if (bdev->bd_block_size != size) {
133 sync_blockdev(bdev);
134 bdev->bd_block_size = size;
135 bdev->bd_inode->i_blkbits = blksize_bits(size);
136 kill_bdev(bdev);
137 }
138 return 0;
139}
140
141EXPORT_SYMBOL(set_blocksize);
142
143int sb_set_blocksize(struct super_block *sb, int size)
144{
1da177e4
LT
145 if (set_blocksize(sb->s_bdev, size))
146 return 0;
147 /* If we get here, we know size is power of two
148 * and it's value is between 512 and PAGE_SIZE */
149 sb->s_blocksize = size;
38885bd4 150 sb->s_blocksize_bits = blksize_bits(size);
1da177e4
LT
151 return sb->s_blocksize;
152}
153
154EXPORT_SYMBOL(sb_set_blocksize);
155
156int sb_min_blocksize(struct super_block *sb, int size)
157{
e1defc4f 158 int minsize = bdev_logical_block_size(sb->s_bdev);
1da177e4
LT
159 if (size < minsize)
160 size = minsize;
161 return sb_set_blocksize(sb, size);
162}
163
164EXPORT_SYMBOL(sb_min_blocksize);
165
166static int
167blkdev_get_block(struct inode *inode, sector_t iblock,
168 struct buffer_head *bh, int create)
169{
1da177e4
LT
170 bh->b_bdev = I_BDEV(inode);
171 bh->b_blocknr = iblock;
172 set_buffer_mapped(bh);
173 return 0;
174}
175
4ebb16ca
DW
176static struct inode *bdev_file_inode(struct file *file)
177{
178 return file->f_mapping->host;
179}
180
78250c02
JA
181static unsigned int dio_bio_write_op(struct kiocb *iocb)
182{
183 unsigned int op = REQ_OP_WRITE | REQ_SYNC | REQ_IDLE;
184
185 /* avoid the need for a I/O completion work item */
186 if (iocb->ki_flags & IOCB_DSYNC)
187 op |= REQ_FUA;
188 return op;
189}
190
189ce2b9
CH
191#define DIO_INLINE_BIO_VECS 4
192
193static void blkdev_bio_end_io_simple(struct bio *bio)
194{
195 struct task_struct *waiter = bio->bi_private;
196
197 WRITE_ONCE(bio->bi_private, NULL);
0619317f 198 blk_wake_io_task(waiter);
189ce2b9
CH
199}
200
201static ssize_t
202__blkdev_direct_IO_simple(struct kiocb *iocb, struct iov_iter *iter,
203 int nr_pages)
204{
205 struct file *file = iocb->ki_filp;
206 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
9fec4a21 207 struct bio_vec inline_vecs[DIO_INLINE_BIO_VECS], *vecs;
189ce2b9
CH
208 loff_t pos = iocb->ki_pos;
209 bool should_dirty = false;
210 struct bio bio;
211 ssize_t ret;
212 blk_qc_t qc;
189ce2b9 213
9a794fb9
JA
214 if ((pos | iov_iter_alignment(iter)) &
215 (bdev_logical_block_size(bdev) - 1))
189ce2b9
CH
216 return -EINVAL;
217
72ecad22
JA
218 if (nr_pages <= DIO_INLINE_BIO_VECS)
219 vecs = inline_vecs;
220 else {
6da2ec56
KC
221 vecs = kmalloc_array(nr_pages, sizeof(struct bio_vec),
222 GFP_KERNEL);
72ecad22
JA
223 if (!vecs)
224 return -ENOMEM;
225 }
226
3a83f467 227 bio_init(&bio, vecs, nr_pages);
74d46992 228 bio_set_dev(&bio, bdev);
4d1a4765 229 bio.bi_iter.bi_sector = pos >> 9;
45d06cf7 230 bio.bi_write_hint = iocb->ki_hint;
189ce2b9
CH
231 bio.bi_private = current;
232 bio.bi_end_io = blkdev_bio_end_io_simple;
074111ca 233 bio.bi_ioprio = iocb->ki_ioprio;
189ce2b9
CH
234
235 ret = bio_iov_iter_get_pages(&bio, iter);
236 if (unlikely(ret))
9362dd11 237 goto out;
189ce2b9
CH
238 ret = bio.bi_iter.bi_size;
239
240 if (iov_iter_rw(iter) == READ) {
78250c02 241 bio.bi_opf = REQ_OP_READ;
189ce2b9
CH
242 if (iter_is_iovec(iter))
243 should_dirty = true;
244 } else {
78250c02 245 bio.bi_opf = dio_bio_write_op(iocb);
189ce2b9
CH
246 task_io_account_write(ret);
247 }
d1e36282 248 if (iocb->ki_flags & IOCB_HIPRI)
0bbb280d 249 bio_set_polled(&bio, iocb);
189ce2b9
CH
250
251 qc = submit_bio(&bio);
252 for (;;) {
1ac5cd49 253 set_current_state(TASK_UNINTERRUPTIBLE);
189ce2b9
CH
254 if (!READ_ONCE(bio.bi_private))
255 break;
256 if (!(iocb->ki_flags & IOCB_HIPRI) ||
0a1b8b87 257 !blk_poll(bdev_get_queue(bdev), qc, true))
189ce2b9
CH
258 io_schedule();
259 }
260 __set_current_state(TASK_RUNNING);
261
9fec4a21 262 bio_release_pages(&bio, should_dirty);
4e4cbee9 263 if (unlikely(bio.bi_status))
c6b1e36c 264 ret = blk_status_to_errno(bio.bi_status);
9ae3b3f5 265
9362dd11
MW
266out:
267 if (vecs != inline_vecs)
268 kfree(vecs);
269
9ae3b3f5
JA
270 bio_uninit(&bio);
271
189ce2b9
CH
272 return ret;
273}
274
542ff7bf
CH
275struct blkdev_dio {
276 union {
277 struct kiocb *iocb;
278 struct task_struct *waiter;
279 };
280 size_t size;
281 atomic_t ref;
282 bool multi_bio : 1;
283 bool should_dirty : 1;
284 bool is_sync : 1;
285 struct bio bio;
286};
287
52190f8a 288static struct bio_set blkdev_dio_pool;
542ff7bf 289
eae83ce1
CH
290static int blkdev_iopoll(struct kiocb *kiocb, bool wait)
291{
292 struct block_device *bdev = I_BDEV(kiocb->ki_filp->f_mapping->host);
293 struct request_queue *q = bdev_get_queue(bdev);
294
295 return blk_poll(q, READ_ONCE(kiocb->ki_cookie), wait);
296}
297
542ff7bf
CH
298static void blkdev_bio_end_io(struct bio *bio)
299{
300 struct blkdev_dio *dio = bio->bi_private;
301 bool should_dirty = dio->should_dirty;
302
a89afe58
JY
303 if (bio->bi_status && !dio->bio.bi_status)
304 dio->bio.bi_status = bio->bi_status;
305
306 if (!dio->multi_bio || atomic_dec_and_test(&dio->ref)) {
542ff7bf
CH
307 if (!dio->is_sync) {
308 struct kiocb *iocb = dio->iocb;
4e4cbee9 309 ssize_t ret;
542ff7bf 310
4e4cbee9 311 if (likely(!dio->bio.bi_status)) {
542ff7bf
CH
312 ret = dio->size;
313 iocb->ki_pos += ret;
4e4cbee9
CH
314 } else {
315 ret = blk_status_to_errno(dio->bio.bi_status);
542ff7bf
CH
316 }
317
318 dio->iocb->ki_complete(iocb, ret, 0);
531724ab
CH
319 if (dio->multi_bio)
320 bio_put(&dio->bio);
542ff7bf
CH
321 } else {
322 struct task_struct *waiter = dio->waiter;
323
324 WRITE_ONCE(dio->waiter, NULL);
0619317f 325 blk_wake_io_task(waiter);
542ff7bf
CH
326 }
327 }
328
329 if (should_dirty) {
330 bio_check_pages_dirty(bio);
331 } else {
57dfe3ce 332 bio_release_pages(bio, false);
542ff7bf
CH
333 bio_put(bio);
334 }
335}
336
b2e895db 337static ssize_t
542ff7bf 338__blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter, int nr_pages)
b2e895db
AM
339{
340 struct file *file = iocb->ki_filp;
4ebb16ca 341 struct inode *inode = bdev_file_inode(file);
542ff7bf 342 struct block_device *bdev = I_BDEV(inode);
64d656a1 343 struct blk_plug plug;
542ff7bf
CH
344 struct blkdev_dio *dio;
345 struct bio *bio;
cb700eb3 346 bool is_poll = (iocb->ki_flags & IOCB_HIPRI) != 0;
690e5325 347 bool is_read = (iov_iter_rw(iter) == READ), is_sync;
6a43074e 348 bool nowait = (iocb->ki_flags & IOCB_NOWAIT) != 0;
542ff7bf
CH
349 loff_t pos = iocb->ki_pos;
350 blk_qc_t qc = BLK_QC_T_NONE;
6a43074e 351 gfp_t gfp;
e15c2ffa 352 int ret;
542ff7bf 353
9a794fb9
JA
354 if ((pos | iov_iter_alignment(iter)) &
355 (bdev_logical_block_size(bdev) - 1))
542ff7bf
CH
356 return -EINVAL;
357
6a43074e
JA
358 if (nowait)
359 gfp = GFP_NOWAIT;
360 else
361 gfp = GFP_KERNEL;
362
363 bio = bio_alloc_bioset(gfp, nr_pages, &blkdev_dio_pool);
364 if (!bio)
365 return -EAGAIN;
542ff7bf
CH
366
367 dio = container_of(bio, struct blkdev_dio, bio);
690e5325 368 dio->is_sync = is_sync = is_sync_kiocb(iocb);
531724ab 369 if (dio->is_sync) {
542ff7bf 370 dio->waiter = current;
531724ab
CH
371 bio_get(bio);
372 } else {
542ff7bf 373 dio->iocb = iocb;
531724ab 374 }
542ff7bf
CH
375
376 dio->size = 0;
377 dio->multi_bio = false;
00e23707 378 dio->should_dirty = is_read && iter_is_iovec(iter);
542ff7bf 379
cb700eb3
JA
380 /*
381 * Don't plug for HIPRI/polled IO, as those should go straight
382 * to issue
383 */
384 if (!is_poll)
385 blk_start_plug(&plug);
386
6a43074e 387 ret = 0;
542ff7bf 388 for (;;) {
74d46992 389 bio_set_dev(bio, bdev);
4d1a4765 390 bio->bi_iter.bi_sector = pos >> 9;
45d06cf7 391 bio->bi_write_hint = iocb->ki_hint;
542ff7bf
CH
392 bio->bi_private = dio;
393 bio->bi_end_io = blkdev_bio_end_io;
074111ca 394 bio->bi_ioprio = iocb->ki_ioprio;
542ff7bf 395
e15c2ffa
JA
396 ret = bio_iov_iter_get_pages(bio, iter);
397 if (unlikely(ret)) {
4e4cbee9 398 bio->bi_status = BLK_STS_IOERR;
542ff7bf
CH
399 bio_endio(bio);
400 break;
401 }
402
403 if (is_read) {
404 bio->bi_opf = REQ_OP_READ;
405 if (dio->should_dirty)
406 bio_set_pages_dirty(bio);
407 } else {
408 bio->bi_opf = dio_bio_write_op(iocb);
409 task_io_account_write(bio->bi_iter.bi_size);
410 }
411
6a43074e
JA
412 /*
413 * Tell underlying layer to not block for resource shortage.
414 * And if we would have blocked, return error inline instead
415 * of through the bio->bi_end_io() callback.
416 */
417 if (nowait)
418 bio->bi_opf |= (REQ_NOWAIT | REQ_NOWAIT_INLINE);
419
542ff7bf
CH
420 pos += bio->bi_iter.bi_size;
421
422 nr_pages = iov_iter_npages(iter, BIO_MAX_PAGES);
423 if (!nr_pages) {
eae83ce1
CH
424 bool polled = false;
425
426 if (iocb->ki_flags & IOCB_HIPRI) {
0bbb280d 427 bio_set_polled(bio, iocb);
eae83ce1
CH
428 polled = true;
429 }
d34513d3 430
e15c2ffa 431 dio->size += bio->bi_iter.bi_size;
542ff7bf 432 qc = submit_bio(bio);
6a43074e 433 if (qc == BLK_QC_T_EAGAIN) {
e15c2ffa
JA
434 dio->size -= bio->bi_iter.bi_size;
435 ret = -EAGAIN;
6a43074e
JA
436 goto error;
437 }
eae83ce1
CH
438
439 if (polled)
440 WRITE_ONCE(iocb->ki_cookie, qc);
542ff7bf
CH
441 break;
442 }
443
444 if (!dio->multi_bio) {
531724ab
CH
445 /*
446 * AIO needs an extra reference to ensure the dio
447 * structure which is embedded into the first bio
448 * stays around.
449 */
450 if (!is_sync)
451 bio_get(bio);
542ff7bf
CH
452 dio->multi_bio = true;
453 atomic_set(&dio->ref, 2);
454 } else {
455 atomic_inc(&dio->ref);
456 }
457
e15c2ffa 458 dio->size += bio->bi_iter.bi_size;
6a43074e
JA
459 qc = submit_bio(bio);
460 if (qc == BLK_QC_T_EAGAIN) {
e15c2ffa
JA
461 dio->size -= bio->bi_iter.bi_size;
462 ret = -EAGAIN;
6a43074e
JA
463 goto error;
464 }
6a43074e
JA
465
466 bio = bio_alloc(gfp, nr_pages);
467 if (!bio) {
e15c2ffa 468 ret = -EAGAIN;
6a43074e
JA
469 goto error;
470 }
542ff7bf 471 }
cb700eb3
JA
472
473 if (!is_poll)
474 blk_finish_plug(&plug);
542ff7bf 475
690e5325 476 if (!is_sync)
542ff7bf
CH
477 return -EIOCBQUEUED;
478
479 for (;;) {
1ac5cd49 480 set_current_state(TASK_UNINTERRUPTIBLE);
542ff7bf
CH
481 if (!READ_ONCE(dio->waiter))
482 break;
483
484 if (!(iocb->ki_flags & IOCB_HIPRI) ||
0a1b8b87 485 !blk_poll(bdev_get_queue(bdev), qc, true))
542ff7bf
CH
486 io_schedule();
487 }
488 __set_current_state(TASK_RUNNING);
489
6a43074e 490out:
36ffc6c1 491 if (!ret)
4e4cbee9 492 ret = blk_status_to_errno(dio->bio.bi_status);
e15c2ffa
JA
493 if (likely(!ret))
494 ret = dio->size;
542ff7bf
CH
495
496 bio_put(&dio->bio);
497 return ret;
6a43074e
JA
498error:
499 if (!is_poll)
500 blk_finish_plug(&plug);
501 goto out;
542ff7bf
CH
502}
503
504static ssize_t
505blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
506{
189ce2b9 507 int nr_pages;
b2e895db 508
72ecad22 509 nr_pages = iov_iter_npages(iter, BIO_MAX_PAGES + 1);
189ce2b9
CH
510 if (!nr_pages)
511 return 0;
72ecad22 512 if (is_sync_kiocb(iocb) && nr_pages <= BIO_MAX_PAGES)
189ce2b9 513 return __blkdev_direct_IO_simple(iocb, iter, nr_pages);
542ff7bf
CH
514
515 return __blkdev_direct_IO(iocb, iter, min(nr_pages, BIO_MAX_PAGES));
516}
517
518static __init int blkdev_init(void)
519{
52190f8a 520 return bioset_init(&blkdev_dio_pool, 4, offsetof(struct blkdev_dio, bio), BIOSET_NEED_BVECS);
b2e895db 521}
542ff7bf 522module_init(blkdev_init);
b2e895db 523
5cee5815
JK
524int __sync_blockdev(struct block_device *bdev, int wait)
525{
526 if (!bdev)
527 return 0;
528 if (!wait)
529 return filemap_flush(bdev->bd_inode->i_mapping);
530 return filemap_write_and_wait(bdev->bd_inode->i_mapping);
531}
532
585d3bc0
NP
533/*
534 * Write out and wait upon all the dirty data associated with a block
535 * device via its mapping. Does not take the superblock lock.
536 */
537int sync_blockdev(struct block_device *bdev)
538{
5cee5815 539 return __sync_blockdev(bdev, 1);
585d3bc0
NP
540}
541EXPORT_SYMBOL(sync_blockdev);
542
543/*
544 * Write out and wait upon all dirty data associated with this
545 * device. Filesystem data as well as the underlying block
546 * device. Takes the superblock lock.
547 */
548int fsync_bdev(struct block_device *bdev)
549{
550 struct super_block *sb = get_super(bdev);
551 if (sb) {
60b0680f 552 int res = sync_filesystem(sb);
585d3bc0
NP
553 drop_super(sb);
554 return res;
555 }
556 return sync_blockdev(bdev);
557}
47e4491b 558EXPORT_SYMBOL(fsync_bdev);
585d3bc0
NP
559
560/**
561 * freeze_bdev -- lock a filesystem and force it into a consistent state
562 * @bdev: blockdevice to lock
563 *
585d3bc0
NP
564 * If a superblock is found on this device, we take the s_umount semaphore
565 * on it to make sure nobody unmounts until the snapshot creation is done.
566 * The reference counter (bd_fsfreeze_count) guarantees that only the last
567 * unfreeze process can unfreeze the frozen filesystem actually when multiple
568 * freeze requests arrive simultaneously. It counts up in freeze_bdev() and
569 * count down in thaw_bdev(). When it becomes 0, thaw_bdev() will unfreeze
570 * actually.
571 */
572struct super_block *freeze_bdev(struct block_device *bdev)
573{
574 struct super_block *sb;
575 int error = 0;
576
577 mutex_lock(&bdev->bd_fsfreeze_mutex);
4504230a
CH
578 if (++bdev->bd_fsfreeze_count > 1) {
579 /*
580 * We don't even need to grab a reference - the first call
581 * to freeze_bdev grab an active reference and only the last
582 * thaw_bdev drops it.
583 */
585d3bc0 584 sb = get_super(bdev);
5bb53c0f
AR
585 if (sb)
586 drop_super(sb);
4504230a
CH
587 mutex_unlock(&bdev->bd_fsfreeze_mutex);
588 return sb;
589 }
590
591 sb = get_active_super(bdev);
592 if (!sb)
593 goto out;
48b6bca6
BM
594 if (sb->s_op->freeze_super)
595 error = sb->s_op->freeze_super(sb);
596 else
597 error = freeze_super(sb);
18e9e510
JB
598 if (error) {
599 deactivate_super(sb);
600 bdev->bd_fsfreeze_count--;
585d3bc0 601 mutex_unlock(&bdev->bd_fsfreeze_mutex);
18e9e510 602 return ERR_PTR(error);
585d3bc0 603 }
18e9e510 604 deactivate_super(sb);
4504230a 605 out:
585d3bc0
NP
606 sync_blockdev(bdev);
607 mutex_unlock(&bdev->bd_fsfreeze_mutex);
4fadd7bb 608 return sb; /* thaw_bdev releases s->s_umount */
585d3bc0
NP
609}
610EXPORT_SYMBOL(freeze_bdev);
611
612/**
613 * thaw_bdev -- unlock filesystem
614 * @bdev: blockdevice to unlock
615 * @sb: associated superblock
616 *
617 * Unlocks the filesystem and marks it writeable again after freeze_bdev().
618 */
619int thaw_bdev(struct block_device *bdev, struct super_block *sb)
620{
4504230a 621 int error = -EINVAL;
585d3bc0
NP
622
623 mutex_lock(&bdev->bd_fsfreeze_mutex);
4504230a 624 if (!bdev->bd_fsfreeze_count)
18e9e510 625 goto out;
4504230a
CH
626
627 error = 0;
628 if (--bdev->bd_fsfreeze_count > 0)
18e9e510 629 goto out;
4504230a
CH
630
631 if (!sb)
18e9e510 632 goto out;
4504230a 633
48b6bca6
BM
634 if (sb->s_op->thaw_super)
635 error = sb->s_op->thaw_super(sb);
636 else
637 error = thaw_super(sb);
997198ba 638 if (error)
18e9e510 639 bdev->bd_fsfreeze_count++;
18e9e510 640out:
585d3bc0 641 mutex_unlock(&bdev->bd_fsfreeze_mutex);
997198ba 642 return error;
585d3bc0
NP
643}
644EXPORT_SYMBOL(thaw_bdev);
645
1da177e4
LT
646static int blkdev_writepage(struct page *page, struct writeback_control *wbc)
647{
648 return block_write_full_page(page, blkdev_get_block, wbc);
649}
650
651static int blkdev_readpage(struct file * file, struct page * page)
652{
653 return block_read_full_page(page, blkdev_get_block);
654}
655
447f05bb
AM
656static int blkdev_readpages(struct file *file, struct address_space *mapping,
657 struct list_head *pages, unsigned nr_pages)
658{
659 return mpage_readpages(mapping, pages, nr_pages, blkdev_get_block);
660}
661
6272b5a5
NP
662static int blkdev_write_begin(struct file *file, struct address_space *mapping,
663 loff_t pos, unsigned len, unsigned flags,
664 struct page **pagep, void **fsdata)
1da177e4 665{
155130a4
CH
666 return block_write_begin(mapping, pos, len, flags, pagep,
667 blkdev_get_block);
1da177e4
LT
668}
669
6272b5a5
NP
670static int blkdev_write_end(struct file *file, struct address_space *mapping,
671 loff_t pos, unsigned len, unsigned copied,
672 struct page *page, void *fsdata)
1da177e4 673{
6272b5a5
NP
674 int ret;
675 ret = block_write_end(file, mapping, pos, len, copied, page, fsdata);
676
677 unlock_page(page);
09cbfeaf 678 put_page(page);
6272b5a5
NP
679
680 return ret;
1da177e4
LT
681}
682
683/*
684 * private llseek:
496ad9aa 685 * for a block special file file_inode(file)->i_size is zero
1da177e4
LT
686 * so we compute the size by hand (just as in block_read/write above)
687 */
965c8e59 688static loff_t block_llseek(struct file *file, loff_t offset, int whence)
1da177e4 689{
4ebb16ca 690 struct inode *bd_inode = bdev_file_inode(file);
1da177e4
LT
691 loff_t retval;
692
5955102c 693 inode_lock(bd_inode);
5d48f3a2 694 retval = fixed_size_llseek(file, offset, whence, i_size_read(bd_inode));
5955102c 695 inode_unlock(bd_inode);
1da177e4
LT
696 return retval;
697}
698
02c24a82 699int blkdev_fsync(struct file *filp, loff_t start, loff_t end, int datasync)
1da177e4 700{
4ebb16ca 701 struct inode *bd_inode = bdev_file_inode(filp);
b8af67e2 702 struct block_device *bdev = I_BDEV(bd_inode);
ab0a9735 703 int error;
da5aa861 704
372cf243 705 error = file_write_and_wait_range(filp, start, end);
da5aa861
RW
706 if (error)
707 return error;
ab0a9735 708
b8af67e2
AB
709 /*
710 * There is no need to serialise calls to blkdev_issue_flush with
711 * i_mutex and doing so causes performance issues with concurrent
712 * O_SYNC writers to a block device.
713 */
dd3932ed 714 error = blkdev_issue_flush(bdev, GFP_KERNEL, NULL);
ab0a9735
CH
715 if (error == -EOPNOTSUPP)
716 error = 0;
b8af67e2 717
ab0a9735 718 return error;
1da177e4 719}
b1dd3b28 720EXPORT_SYMBOL(blkdev_fsync);
1da177e4 721
47a191fd
MW
722/**
723 * bdev_read_page() - Start reading a page from a block device
724 * @bdev: The device to read the page from
725 * @sector: The offset on the device to read the page to (need not be aligned)
726 * @page: The page to read
727 *
728 * On entry, the page should be locked. It will be unlocked when the page
729 * has been read. If the block driver implements rw_page synchronously,
730 * that will be true on exit from this function, but it need not be.
731 *
732 * Errors returned by this function are usually "soft", eg out of memory, or
733 * queue full; callers should try a different route to read this page rather
734 * than propagate an error back up the stack.
735 *
736 * Return: negative errno if an error occurs, 0 if submission was successful.
737 */
738int bdev_read_page(struct block_device *bdev, sector_t sector,
739 struct page *page)
740{
741 const struct block_device_operations *ops = bdev->bd_disk->fops;
2e6edc95
DW
742 int result = -EOPNOTSUPP;
743
f68eb1e7 744 if (!ops->rw_page || bdev_get_integrity(bdev))
2e6edc95
DW
745 return result;
746
3a0a5299 747 result = blk_queue_enter(bdev->bd_queue, 0);
2e6edc95
DW
748 if (result)
749 return result;
3f289dcb
TH
750 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
751 REQ_OP_READ);
2e6edc95
DW
752 blk_queue_exit(bdev->bd_queue);
753 return result;
47a191fd
MW
754}
755EXPORT_SYMBOL_GPL(bdev_read_page);
756
757/**
758 * bdev_write_page() - Start writing a page to a block device
759 * @bdev: The device to write the page to
760 * @sector: The offset on the device to write the page to (need not be aligned)
761 * @page: The page to write
762 * @wbc: The writeback_control for the write
763 *
764 * On entry, the page should be locked and not currently under writeback.
765 * On exit, if the write started successfully, the page will be unlocked and
766 * under writeback. If the write failed already (eg the driver failed to
767 * queue the page to the device), the page will still be locked. If the
768 * caller is a ->writepage implementation, it will need to unlock the page.
769 *
770 * Errors returned by this function are usually "soft", eg out of memory, or
771 * queue full; callers should try a different route to write this page rather
772 * than propagate an error back up the stack.
773 *
774 * Return: negative errno if an error occurs, 0 if submission was successful.
775 */
776int bdev_write_page(struct block_device *bdev, sector_t sector,
777 struct page *page, struct writeback_control *wbc)
778{
779 int result;
47a191fd 780 const struct block_device_operations *ops = bdev->bd_disk->fops;
2e6edc95 781
f68eb1e7 782 if (!ops->rw_page || bdev_get_integrity(bdev))
47a191fd 783 return -EOPNOTSUPP;
3a0a5299 784 result = blk_queue_enter(bdev->bd_queue, 0);
2e6edc95
DW
785 if (result)
786 return result;
787
47a191fd 788 set_page_writeback(page);
3f289dcb
TH
789 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
790 REQ_OP_WRITE);
f892760a 791 if (result) {
47a191fd 792 end_page_writeback(page);
f892760a
MW
793 } else {
794 clean_page_buffers(page);
47a191fd 795 unlock_page(page);
f892760a 796 }
2e6edc95 797 blk_queue_exit(bdev->bd_queue);
47a191fd
MW
798 return result;
799}
800EXPORT_SYMBOL_GPL(bdev_write_page);
801
1da177e4
LT
802/*
803 * pseudo-fs
804 */
805
806static __cacheline_aligned_in_smp DEFINE_SPINLOCK(bdev_lock);
e18b890b 807static struct kmem_cache * bdev_cachep __read_mostly;
1da177e4
LT
808
809static struct inode *bdev_alloc_inode(struct super_block *sb)
810{
e94b1766 811 struct bdev_inode *ei = kmem_cache_alloc(bdev_cachep, GFP_KERNEL);
1da177e4
LT
812 if (!ei)
813 return NULL;
814 return &ei->vfs_inode;
815}
816
41149cb0 817static void bdev_free_inode(struct inode *inode)
1da177e4 818{
41149cb0 819 kmem_cache_free(bdev_cachep, BDEV_I(inode));
fa0d7e3d
NP
820}
821
51cc5068 822static void init_once(void *foo)
1da177e4
LT
823{
824 struct bdev_inode *ei = (struct bdev_inode *) foo;
825 struct block_device *bdev = &ei->bdev;
826
a35afb83
CL
827 memset(bdev, 0, sizeof(*bdev));
828 mutex_init(&bdev->bd_mutex);
a35afb83 829 INIT_LIST_HEAD(&bdev->bd_list);
49731baa
TH
830#ifdef CONFIG_SYSFS
831 INIT_LIST_HEAD(&bdev->bd_holder_disks);
832#endif
a5a79d00 833 bdev->bd_bdi = &noop_backing_dev_info;
a35afb83 834 inode_init_once(&ei->vfs_inode);
fcccf502
TS
835 /* Initialize mutex for freeze. */
836 mutex_init(&bdev->bd_fsfreeze_mutex);
1da177e4
LT
837}
838
b57922d9 839static void bdev_evict_inode(struct inode *inode)
1da177e4
LT
840{
841 struct block_device *bdev = &BDEV_I(inode)->bdev;
91b0abe3 842 truncate_inode_pages_final(&inode->i_data);
b57922d9 843 invalidate_inode_buffers(inode); /* is it needed here? */
dbd5768f 844 clear_inode(inode);
1da177e4 845 spin_lock(&bdev_lock);
1da177e4
LT
846 list_del_init(&bdev->bd_list);
847 spin_unlock(&bdev_lock);
f759741d
JK
848 /* Detach inode from wb early as bdi_put() may free bdi->wb */
849 inode_detach_wb(inode);
a5a79d00 850 if (bdev->bd_bdi != &noop_backing_dev_info) {
b1d2dc56 851 bdi_put(bdev->bd_bdi);
a5a79d00
JK
852 bdev->bd_bdi = &noop_backing_dev_info;
853 }
1da177e4
LT
854}
855
ee9b6d61 856static const struct super_operations bdev_sops = {
1da177e4
LT
857 .statfs = simple_statfs,
858 .alloc_inode = bdev_alloc_inode,
41149cb0 859 .free_inode = bdev_free_inode,
1da177e4 860 .drop_inode = generic_delete_inode,
b57922d9 861 .evict_inode = bdev_evict_inode,
1da177e4
LT
862};
863
9030d16e 864static int bd_init_fs_context(struct fs_context *fc)
1da177e4 865{
9030d16e
DH
866 struct pseudo_fs_context *ctx = init_pseudo(fc, BDEVFS_MAGIC);
867 if (!ctx)
868 return -ENOMEM;
869 fc->s_iflags |= SB_I_CGROUPWB;
870 ctx->ops = &bdev_sops;
871 return 0;
1da177e4
LT
872}
873
874static struct file_system_type bd_type = {
875 .name = "bdev",
9030d16e 876 .init_fs_context = bd_init_fs_context,
1da177e4
LT
877 .kill_sb = kill_anon_super,
878};
879
a212b105
TH
880struct super_block *blockdev_superblock __read_mostly;
881EXPORT_SYMBOL_GPL(blockdev_superblock);
1da177e4
LT
882
883void __init bdev_cache_init(void)
884{
885 int err;
ace8577a 886 static struct vfsmount *bd_mnt;
c2acf7b9 887
1da177e4 888 bdev_cachep = kmem_cache_create("bdev_cache", sizeof(struct bdev_inode),
fffb60f9 889 0, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
5d097056 890 SLAB_MEM_SPREAD|SLAB_ACCOUNT|SLAB_PANIC),
20c2df83 891 init_once);
1da177e4
LT
892 err = register_filesystem(&bd_type);
893 if (err)
894 panic("Cannot register bdev pseudo-fs");
895 bd_mnt = kern_mount(&bd_type);
1da177e4
LT
896 if (IS_ERR(bd_mnt))
897 panic("Cannot create bdev pseudo-fs");
ace8577a 898 blockdev_superblock = bd_mnt->mnt_sb; /* For writeback */
1da177e4
LT
899}
900
901/*
902 * Most likely _very_ bad one - but then it's hardly critical for small
903 * /dev and can be fixed when somebody will need really large one.
904 * Keep in mind that it will be fed through icache hash function too.
905 */
906static inline unsigned long hash(dev_t dev)
907{
908 return MAJOR(dev)+MINOR(dev);
909}
910
911static int bdev_test(struct inode *inode, void *data)
912{
913 return BDEV_I(inode)->bdev.bd_dev == *(dev_t *)data;
914}
915
916static int bdev_set(struct inode *inode, void *data)
917{
918 BDEV_I(inode)->bdev.bd_dev = *(dev_t *)data;
919 return 0;
920}
921
922static LIST_HEAD(all_bdevs);
923
f44f1ab5
JK
924/*
925 * If there is a bdev inode for this device, unhash it so that it gets evicted
926 * as soon as last inode reference is dropped.
927 */
928void bdev_unhash_inode(dev_t dev)
929{
930 struct inode *inode;
931
932 inode = ilookup5(blockdev_superblock, hash(dev), bdev_test, &dev);
933 if (inode) {
934 remove_inode_hash(inode);
935 iput(inode);
936 }
937}
938
1da177e4
LT
939struct block_device *bdget(dev_t dev)
940{
941 struct block_device *bdev;
942 struct inode *inode;
943
c2acf7b9 944 inode = iget5_locked(blockdev_superblock, hash(dev),
1da177e4
LT
945 bdev_test, bdev_set, &dev);
946
947 if (!inode)
948 return NULL;
949
950 bdev = &BDEV_I(inode)->bdev;
951
952 if (inode->i_state & I_NEW) {
953 bdev->bd_contains = NULL;
782b94cd 954 bdev->bd_super = NULL;
1da177e4 955 bdev->bd_inode = inode;
93407472 956 bdev->bd_block_size = i_blocksize(inode);
1da177e4
LT
957 bdev->bd_part_count = 0;
958 bdev->bd_invalidated = 0;
959 inode->i_mode = S_IFBLK;
960 inode->i_rdev = dev;
961 inode->i_bdev = bdev;
962 inode->i_data.a_ops = &def_blk_aops;
963 mapping_set_gfp_mask(&inode->i_data, GFP_USER);
1da177e4
LT
964 spin_lock(&bdev_lock);
965 list_add(&bdev->bd_list, &all_bdevs);
966 spin_unlock(&bdev_lock);
967 unlock_new_inode(inode);
968 }
969 return bdev;
970}
971
972EXPORT_SYMBOL(bdget);
973
dddac6a7
AJ
974/**
975 * bdgrab -- Grab a reference to an already referenced block device
976 * @bdev: Block device to grab a reference to.
977 */
978struct block_device *bdgrab(struct block_device *bdev)
979{
7de9c6ee 980 ihold(bdev->bd_inode);
dddac6a7
AJ
981 return bdev;
982}
c1681bf8 983EXPORT_SYMBOL(bdgrab);
dddac6a7 984
1da177e4
LT
985long nr_blockdev_pages(void)
986{
203a2935 987 struct block_device *bdev;
1da177e4
LT
988 long ret = 0;
989 spin_lock(&bdev_lock);
203a2935 990 list_for_each_entry(bdev, &all_bdevs, bd_list) {
1da177e4
LT
991 ret += bdev->bd_inode->i_mapping->nrpages;
992 }
993 spin_unlock(&bdev_lock);
994 return ret;
995}
996
997void bdput(struct block_device *bdev)
998{
999 iput(bdev->bd_inode);
1000}
1001
1002EXPORT_SYMBOL(bdput);
1003
1004static struct block_device *bd_acquire(struct inode *inode)
1005{
1006 struct block_device *bdev;
09d967c6 1007
1da177e4
LT
1008 spin_lock(&bdev_lock);
1009 bdev = inode->i_bdev;
cccd9fb9 1010 if (bdev && !inode_unhashed(bdev->bd_inode)) {
ed8a9d2c 1011 bdgrab(bdev);
1da177e4
LT
1012 spin_unlock(&bdev_lock);
1013 return bdev;
1014 }
1015 spin_unlock(&bdev_lock);
09d967c6 1016
cccd9fb9
JK
1017 /*
1018 * i_bdev references block device inode that was already shut down
1019 * (corresponding device got removed). Remove the reference and look
1020 * up block device inode again just in case new device got
1021 * reestablished under the same device number.
1022 */
1023 if (bdev)
1024 bd_forget(inode);
1025
1da177e4
LT
1026 bdev = bdget(inode->i_rdev);
1027 if (bdev) {
1028 spin_lock(&bdev_lock);
09d967c6
OH
1029 if (!inode->i_bdev) {
1030 /*
7de9c6ee 1031 * We take an additional reference to bd_inode,
09d967c6
OH
1032 * and it's released in clear_inode() of inode.
1033 * So, we can access it via ->i_mapping always
1034 * without igrab().
1035 */
ed8a9d2c 1036 bdgrab(bdev);
09d967c6
OH
1037 inode->i_bdev = bdev;
1038 inode->i_mapping = bdev->bd_inode->i_mapping;
09d967c6 1039 }
1da177e4
LT
1040 spin_unlock(&bdev_lock);
1041 }
1042 return bdev;
1043}
1044
1045/* Call when you free inode */
1046
1047void bd_forget(struct inode *inode)
1048{
09d967c6
OH
1049 struct block_device *bdev = NULL;
1050
1da177e4 1051 spin_lock(&bdev_lock);
b4ea2eaa
YH
1052 if (!sb_is_blkdev_sb(inode->i_sb))
1053 bdev = inode->i_bdev;
a4a4f943
AV
1054 inode->i_bdev = NULL;
1055 inode->i_mapping = &inode->i_data;
1da177e4 1056 spin_unlock(&bdev_lock);
09d967c6
OH
1057
1058 if (bdev)
ed8a9d2c 1059 bdput(bdev);
1da177e4
LT
1060}
1061
1a3cbbc5
TH
1062/**
1063 * bd_may_claim - test whether a block device can be claimed
1064 * @bdev: block device of interest
1065 * @whole: whole block device containing @bdev, may equal @bdev
1066 * @holder: holder trying to claim @bdev
1067 *
25985edc 1068 * Test whether @bdev can be claimed by @holder.
1a3cbbc5
TH
1069 *
1070 * CONTEXT:
1071 * spin_lock(&bdev_lock).
1072 *
1073 * RETURNS:
1074 * %true if @bdev can be claimed, %false otherwise.
1075 */
1076static bool bd_may_claim(struct block_device *bdev, struct block_device *whole,
1077 void *holder)
1da177e4 1078{
1da177e4 1079 if (bdev->bd_holder == holder)
1a3cbbc5 1080 return true; /* already a holder */
1da177e4 1081 else if (bdev->bd_holder != NULL)
1a3cbbc5 1082 return false; /* held by someone else */
bcc7f5b4 1083 else if (whole == bdev)
1a3cbbc5 1084 return true; /* is a whole device which isn't held */
1da177e4 1085
e525fd89 1086 else if (whole->bd_holder == bd_may_claim)
1a3cbbc5
TH
1087 return true; /* is a partition of a device that is being partitioned */
1088 else if (whole->bd_holder != NULL)
1089 return false; /* is a partition of a held device */
1da177e4 1090 else
1a3cbbc5
TH
1091 return true; /* is a partition of an un-held device */
1092}
1093
6b4517a7
TH
1094/**
1095 * bd_prepare_to_claim - prepare to claim a block device
1096 * @bdev: block device of interest
1097 * @whole: the whole device containing @bdev, may equal @bdev
1098 * @holder: holder trying to claim @bdev
1099 *
1100 * Prepare to claim @bdev. This function fails if @bdev is already
1101 * claimed by another holder and waits if another claiming is in
1102 * progress. This function doesn't actually claim. On successful
1103 * return, the caller has ownership of bd_claiming and bd_holder[s].
1104 *
1105 * CONTEXT:
1106 * spin_lock(&bdev_lock). Might release bdev_lock, sleep and regrab
1107 * it multiple times.
1108 *
1109 * RETURNS:
1110 * 0 if @bdev can be claimed, -EBUSY otherwise.
1111 */
1112static int bd_prepare_to_claim(struct block_device *bdev,
1113 struct block_device *whole, void *holder)
1114{
1115retry:
1116 /* if someone else claimed, fail */
1117 if (!bd_may_claim(bdev, whole, holder))
1118 return -EBUSY;
1119
e75aa858
TH
1120 /* if claiming is already in progress, wait for it to finish */
1121 if (whole->bd_claiming) {
6b4517a7
TH
1122 wait_queue_head_t *wq = bit_waitqueue(&whole->bd_claiming, 0);
1123 DEFINE_WAIT(wait);
1124
1125 prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
1126 spin_unlock(&bdev_lock);
1127 schedule();
1128 finish_wait(wq, &wait);
1129 spin_lock(&bdev_lock);
1130 goto retry;
1131 }
1132
1133 /* yay, all mine */
1134 return 0;
1135}
1136
560e7cb2
JK
1137static struct gendisk *bdev_get_gendisk(struct block_device *bdev, int *partno)
1138{
1139 struct gendisk *disk = get_gendisk(bdev->bd_dev, partno);
1140
1141 if (!disk)
1142 return NULL;
1143 /*
1144 * Now that we hold gendisk reference we make sure bdev we looked up is
1145 * not stale. If it is, it means device got removed and created before
1146 * we looked up gendisk and we fail open in such case. Associating
1147 * unhashed bdev with newly created gendisk could lead to two bdevs
1148 * (and thus two independent caches) being associated with one device
1149 * which is bad.
1150 */
1151 if (inode_unhashed(bdev->bd_inode)) {
1152 put_disk_and_module(disk);
1153 return NULL;
1154 }
1155 return disk;
1156}
1157
6b4517a7
TH
1158/**
1159 * bd_start_claiming - start claiming a block device
1160 * @bdev: block device of interest
1161 * @holder: holder trying to claim @bdev
1162 *
1163 * @bdev is about to be opened exclusively. Check @bdev can be opened
1164 * exclusively and mark that an exclusive open is in progress. Each
1165 * successful call to this function must be matched with a call to
b0018361
NP
1166 * either bd_finish_claiming() or bd_abort_claiming() (which do not
1167 * fail).
1168 *
1169 * This function is used to gain exclusive access to the block device
1170 * without actually causing other exclusive open attempts to fail. It
1171 * should be used when the open sequence itself requires exclusive
1172 * access but may subsequently fail.
6b4517a7
TH
1173 *
1174 * CONTEXT:
1175 * Might sleep.
1176 *
1177 * RETURNS:
1178 * Pointer to the block device containing @bdev on success, ERR_PTR()
1179 * value on failure.
1180 */
89e524c0 1181struct block_device *bd_start_claiming(struct block_device *bdev, void *holder)
6b4517a7
TH
1182{
1183 struct gendisk *disk;
1184 struct block_device *whole;
1185 int partno, err;
1186
1187 might_sleep();
1188
1189 /*
1190 * @bdev might not have been initialized properly yet, look up
1191 * and grab the outer block device the hard way.
1192 */
560e7cb2 1193 disk = bdev_get_gendisk(bdev, &partno);
6b4517a7
TH
1194 if (!disk)
1195 return ERR_PTR(-ENXIO);
1196
d4c208b8
TH
1197 /*
1198 * Normally, @bdev should equal what's returned from bdget_disk()
1199 * if partno is 0; however, some drivers (floppy) use multiple
1200 * bdev's for the same physical device and @bdev may be one of the
1201 * aliases. Keep @bdev if partno is 0. This means claimer
1202 * tracking is broken for those devices but it has always been that
1203 * way.
1204 */
1205 if (partno)
1206 whole = bdget_disk(disk, 0);
1207 else
1208 whole = bdgrab(bdev);
1209
9df6c299 1210 put_disk_and_module(disk);
6b4517a7
TH
1211 if (!whole)
1212 return ERR_PTR(-ENOMEM);
1213
1214 /* prepare to claim, if successful, mark claiming in progress */
1215 spin_lock(&bdev_lock);
1216
1217 err = bd_prepare_to_claim(bdev, whole, holder);
1218 if (err == 0) {
1219 whole->bd_claiming = holder;
1220 spin_unlock(&bdev_lock);
1221 return whole;
1222 } else {
1223 spin_unlock(&bdev_lock);
1224 bdput(whole);
1225 return ERR_PTR(err);
1226 }
1227}
89e524c0
JK
1228EXPORT_SYMBOL(bd_start_claiming);
1229
1230static void bd_clear_claiming(struct block_device *whole, void *holder)
1231{
1232 lockdep_assert_held(&bdev_lock);
1233 /* tell others that we're done */
1234 BUG_ON(whole->bd_claiming != holder);
1235 whole->bd_claiming = NULL;
1236 wake_up_bit(&whole->bd_claiming, 0);
1237}
1238
1239/**
1240 * bd_finish_claiming - finish claiming of a block device
1241 * @bdev: block device of interest
1242 * @whole: whole block device (returned from bd_start_claiming())
1243 * @holder: holder that has claimed @bdev
1244 *
1245 * Finish exclusive open of a block device. Mark the device as exlusively
1246 * open by the holder and wake up all waiters for exclusive open to finish.
1247 */
1248void bd_finish_claiming(struct block_device *bdev, struct block_device *whole,
1249 void *holder)
1250{
1251 spin_lock(&bdev_lock);
1252 BUG_ON(!bd_may_claim(bdev, whole, holder));
1253 /*
1254 * Note that for a whole device bd_holders will be incremented twice,
1255 * and bd_holder will be set to bd_may_claim before being set to holder
1256 */
1257 whole->bd_holders++;
1258 whole->bd_holder = bd_may_claim;
1259 bdev->bd_holders++;
1260 bdev->bd_holder = holder;
1261 bd_clear_claiming(whole, holder);
1262 spin_unlock(&bdev_lock);
1263}
1264EXPORT_SYMBOL(bd_finish_claiming);
1265
1266/**
1267 * bd_abort_claiming - abort claiming of a block device
1268 * @bdev: block device of interest
1269 * @whole: whole block device (returned from bd_start_claiming())
1270 * @holder: holder that has claimed @bdev
1271 *
1272 * Abort claiming of a block device when the exclusive open failed. This can be
1273 * also used when exclusive open is not actually desired and we just needed
1274 * to block other exclusive openers for a while.
1275 */
1276void bd_abort_claiming(struct block_device *bdev, struct block_device *whole,
1277 void *holder)
1278{
1279 spin_lock(&bdev_lock);
1280 bd_clear_claiming(whole, holder);
1281 spin_unlock(&bdev_lock);
1282}
1283EXPORT_SYMBOL(bd_abort_claiming);
6b4517a7 1284
641dc636 1285#ifdef CONFIG_SYSFS
49731baa
TH
1286struct bd_holder_disk {
1287 struct list_head list;
1288 struct gendisk *disk;
1289 int refcnt;
1290};
1291
1292static struct bd_holder_disk *bd_find_holder_disk(struct block_device *bdev,
1293 struct gendisk *disk)
1294{
1295 struct bd_holder_disk *holder;
1296
1297 list_for_each_entry(holder, &bdev->bd_holder_disks, list)
1298 if (holder->disk == disk)
1299 return holder;
1300 return NULL;
1301}
1302
4d7dd8fd 1303static int add_symlink(struct kobject *from, struct kobject *to)
641dc636 1304{
4d7dd8fd 1305 return sysfs_create_link(from, to, kobject_name(to));
641dc636
JN
1306}
1307
1308static void del_symlink(struct kobject *from, struct kobject *to)
1309{
641dc636
JN
1310 sysfs_remove_link(from, kobject_name(to));
1311}
1312
df6c0cd9 1313/**
e09b457b
TH
1314 * bd_link_disk_holder - create symlinks between holding disk and slave bdev
1315 * @bdev: the claimed slave bdev
1316 * @disk: the holding disk
df6c0cd9 1317 *
49731baa
TH
1318 * DON'T USE THIS UNLESS YOU'RE ALREADY USING IT.
1319 *
e09b457b 1320 * This functions creates the following sysfs symlinks.
641dc636 1321 *
e09b457b
TH
1322 * - from "slaves" directory of the holder @disk to the claimed @bdev
1323 * - from "holders" directory of the @bdev to the holder @disk
641dc636 1324 *
e09b457b
TH
1325 * For example, if /dev/dm-0 maps to /dev/sda and disk for dm-0 is
1326 * passed to bd_link_disk_holder(), then:
641dc636 1327 *
e09b457b
TH
1328 * /sys/block/dm-0/slaves/sda --> /sys/block/sda
1329 * /sys/block/sda/holders/dm-0 --> /sys/block/dm-0
641dc636 1330 *
e09b457b
TH
1331 * The caller must have claimed @bdev before calling this function and
1332 * ensure that both @bdev and @disk are valid during the creation and
1333 * lifetime of these symlinks.
641dc636 1334 *
e09b457b
TH
1335 * CONTEXT:
1336 * Might sleep.
641dc636 1337 *
e09b457b
TH
1338 * RETURNS:
1339 * 0 on success, -errno on failure.
641dc636 1340 */
e09b457b 1341int bd_link_disk_holder(struct block_device *bdev, struct gendisk *disk)
641dc636 1342{
49731baa 1343 struct bd_holder_disk *holder;
e09b457b 1344 int ret = 0;
641dc636 1345
2e7b651d 1346 mutex_lock(&bdev->bd_mutex);
df6c0cd9 1347
49731baa 1348 WARN_ON_ONCE(!bdev->bd_holder);
4e91672c 1349
e09b457b
TH
1350 /* FIXME: remove the following once add_disk() handles errors */
1351 if (WARN_ON(!disk->slave_dir || !bdev->bd_part->holder_dir))
1352 goto out_unlock;
4e91672c 1353
49731baa
TH
1354 holder = bd_find_holder_disk(bdev, disk);
1355 if (holder) {
1356 holder->refcnt++;
e09b457b 1357 goto out_unlock;
49731baa 1358 }
641dc636 1359
49731baa
TH
1360 holder = kzalloc(sizeof(*holder), GFP_KERNEL);
1361 if (!holder) {
1362 ret = -ENOMEM;
e09b457b
TH
1363 goto out_unlock;
1364 }
641dc636 1365
49731baa
TH
1366 INIT_LIST_HEAD(&holder->list);
1367 holder->disk = disk;
1368 holder->refcnt = 1;
1369
1370 ret = add_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
1371 if (ret)
1372 goto out_free;
1373
1374 ret = add_symlink(bdev->bd_part->holder_dir, &disk_to_dev(disk)->kobj);
1375 if (ret)
1376 goto out_del;
e7407d16
TH
1377 /*
1378 * bdev could be deleted beneath us which would implicitly destroy
1379 * the holder directory. Hold on to it.
1380 */
1381 kobject_get(bdev->bd_part->holder_dir);
49731baa
TH
1382
1383 list_add(&holder->list, &bdev->bd_holder_disks);
1384 goto out_unlock;
1385
1386out_del:
1387 del_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
1388out_free:
1389 kfree(holder);
e09b457b 1390out_unlock:
b4cf1b72 1391 mutex_unlock(&bdev->bd_mutex);
e09b457b 1392 return ret;
641dc636 1393}
e09b457b 1394EXPORT_SYMBOL_GPL(bd_link_disk_holder);
641dc636 1395
49731baa
TH
1396/**
1397 * bd_unlink_disk_holder - destroy symlinks created by bd_link_disk_holder()
1398 * @bdev: the calimed slave bdev
1399 * @disk: the holding disk
1400 *
1401 * DON'T USE THIS UNLESS YOU'RE ALREADY USING IT.
1402 *
1403 * CONTEXT:
1404 * Might sleep.
1405 */
1406void bd_unlink_disk_holder(struct block_device *bdev, struct gendisk *disk)
641dc636 1407{
49731baa 1408 struct bd_holder_disk *holder;
641dc636 1409
49731baa 1410 mutex_lock(&bdev->bd_mutex);
641dc636 1411
49731baa
TH
1412 holder = bd_find_holder_disk(bdev, disk);
1413
1414 if (!WARN_ON_ONCE(holder == NULL) && !--holder->refcnt) {
1415 del_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
1416 del_symlink(bdev->bd_part->holder_dir,
1417 &disk_to_dev(disk)->kobj);
e7407d16 1418 kobject_put(bdev->bd_part->holder_dir);
49731baa
TH
1419 list_del_init(&holder->list);
1420 kfree(holder);
1421 }
1422
1423 mutex_unlock(&bdev->bd_mutex);
1da177e4 1424}
49731baa 1425EXPORT_SYMBOL_GPL(bd_unlink_disk_holder);
641dc636 1426#endif
1da177e4 1427
56ade44b
AP
1428/**
1429 * flush_disk - invalidates all buffer-cache entries on a disk
1430 *
1431 * @bdev: struct block device to be flushed
e6eb5ce1 1432 * @kill_dirty: flag to guide handling of dirty inodes
56ade44b
AP
1433 *
1434 * Invalidates all buffer-cache entries on a disk. It should be called
1435 * when a disk has been changed -- either by a media change or online
1436 * resize.
1437 */
93b270f7 1438static void flush_disk(struct block_device *bdev, bool kill_dirty)
56ade44b 1439{
93b270f7 1440 if (__invalidate_device(bdev, kill_dirty)) {
56ade44b 1441 printk(KERN_WARNING "VFS: busy inodes on changed media or "
424081f3
DM
1442 "resized disk %s\n",
1443 bdev->bd_disk ? bdev->bd_disk->disk_name : "");
56ade44b
AP
1444 }
1445
1446 if (!bdev->bd_disk)
1447 return;
d27769ec 1448 if (disk_part_scan_enabled(bdev->bd_disk))
56ade44b
AP
1449 bdev->bd_invalidated = 1;
1450}
1451
c3279d14 1452/**
57d1b536 1453 * check_disk_size_change - checks for disk size change and adjusts bdev size.
c3279d14
AP
1454 * @disk: struct gendisk to check
1455 * @bdev: struct bdev to adjust.
5afb7835 1456 * @verbose: if %true log a message about a size change if there is any
c3279d14
AP
1457 *
1458 * This routine checks to see if the bdev size does not match the disk size
849cf559 1459 * and adjusts it if it differs. When shrinking the bdev size, its all caches
1460 * are freed.
c3279d14 1461 */
5afb7835
CH
1462void check_disk_size_change(struct gendisk *disk, struct block_device *bdev,
1463 bool verbose)
c3279d14
AP
1464{
1465 loff_t disk_size, bdev_size;
1466
1467 disk_size = (loff_t)get_capacity(disk) << 9;
1468 bdev_size = i_size_read(bdev->bd_inode);
1469 if (disk_size != bdev_size) {
5afb7835
CH
1470 if (verbose) {
1471 printk(KERN_INFO
1472 "%s: detected capacity change from %lld to %lld\n",
1473 disk->disk_name, bdev_size, disk_size);
1474 }
c3279d14 1475 i_size_write(bdev->bd_inode, disk_size);
849cf559 1476 if (bdev_size > disk_size)
1477 flush_disk(bdev, false);
c3279d14
AP
1478 }
1479}
c3279d14 1480
0c002c2f 1481/**
57d1b536 1482 * revalidate_disk - wrapper for lower-level driver's revalidate_disk call-back
0c002c2f
AP
1483 * @disk: struct gendisk to be revalidated
1484 *
1485 * This routine is a wrapper for lower-level driver's revalidate_disk
1486 * call-backs. It is used to do common pre and post operations needed
1487 * for all revalidate_disk operations.
1488 */
1489int revalidate_disk(struct gendisk *disk)
1490{
1491 int ret = 0;
1492
1493 if (disk->fops->revalidate_disk)
1494 ret = disk->fops->revalidate_disk(disk);
c3279d14 1495
31cb1d64
JK
1496 /*
1497 * Hidden disks don't have associated bdev so there's no point in
1498 * revalidating it.
1499 */
1500 if (!(disk->flags & GENHD_FL_HIDDEN)) {
1501 struct block_device *bdev = bdget_disk(disk, 0);
1502
1503 if (!bdev)
1504 return ret;
1505
1506 mutex_lock(&bdev->bd_mutex);
1507 check_disk_size_change(disk, bdev, ret == 0);
1508 bdev->bd_invalidated = 0;
1509 mutex_unlock(&bdev->bd_mutex);
1510 bdput(bdev);
1511 }
0c002c2f
AP
1512 return ret;
1513}
1514EXPORT_SYMBOL(revalidate_disk);
1515
1da177e4
LT
1516/*
1517 * This routine checks whether a removable media has been changed,
1518 * and invalidates all buffer-cache-entries in that case. This
1519 * is a relatively slow routine, so we have to try to minimize using
1520 * it. Thus it is called only upon a 'mount' or 'open'. This
1521 * is the best way of combining speed and utility, I think.
1522 * People changing diskettes in the middle of an operation deserve
1523 * to lose :-)
1524 */
1525int check_disk_change(struct block_device *bdev)
1526{
1527 struct gendisk *disk = bdev->bd_disk;
83d5cde4 1528 const struct block_device_operations *bdops = disk->fops;
77ea887e 1529 unsigned int events;
1da177e4 1530
77ea887e
TH
1531 events = disk_clear_events(disk, DISK_EVENT_MEDIA_CHANGE |
1532 DISK_EVENT_EJECT_REQUEST);
1533 if (!(events & DISK_EVENT_MEDIA_CHANGE))
1da177e4
LT
1534 return 0;
1535
93b270f7 1536 flush_disk(bdev, true);
1da177e4
LT
1537 if (bdops->revalidate_disk)
1538 bdops->revalidate_disk(bdev->bd_disk);
1da177e4
LT
1539 return 1;
1540}
1541
1542EXPORT_SYMBOL(check_disk_change);
1543
1544void bd_set_size(struct block_device *bdev, loff_t size)
1545{
5955102c 1546 inode_lock(bdev->bd_inode);
d646a02a 1547 i_size_write(bdev->bd_inode, size);
5955102c 1548 inode_unlock(bdev->bd_inode);
1da177e4
LT
1549}
1550EXPORT_SYMBOL(bd_set_size);
1551
4385bab1 1552static void __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part);
37be4124 1553
6d740cd5
PZ
1554/*
1555 * bd_mutex locking:
1556 *
1557 * mutex_lock(part->bd_mutex)
1558 * mutex_lock_nested(whole->bd_mutex, 1)
1559 */
1560
572c4892 1561static int __blkdev_get(struct block_device *bdev, fmode_t mode, int for_part)
1da177e4 1562{
1da177e4 1563 struct gendisk *disk;
7db9cfd3 1564 int ret;
cf771cb5 1565 int partno;
fe6e9c1f 1566 int perm = 0;
89736653 1567 bool first_open = false;
fe6e9c1f 1568
572c4892 1569 if (mode & FMODE_READ)
fe6e9c1f 1570 perm |= MAY_READ;
572c4892 1571 if (mode & FMODE_WRITE)
fe6e9c1f
AV
1572 perm |= MAY_WRITE;
1573 /*
1574 * hooks: /n/, see "layering violations".
1575 */
b7300b78
CW
1576 if (!for_part) {
1577 ret = devcgroup_inode_permission(bdev->bd_inode, perm);
1578 if (ret != 0) {
1579 bdput(bdev);
1580 return ret;
1581 }
82666020 1582 }
7db9cfd3 1583
d3374825 1584 restart:
0762b8bd 1585
89f97496 1586 ret = -ENXIO;
560e7cb2 1587 disk = bdev_get_gendisk(bdev, &partno);
0762b8bd 1588 if (!disk)
6e9624b8 1589 goto out;
1da177e4 1590
69e02c59 1591 disk_block_events(disk);
6796bf54 1592 mutex_lock_nested(&bdev->bd_mutex, for_part);
1da177e4 1593 if (!bdev->bd_openers) {
89736653 1594 first_open = true;
1da177e4 1595 bdev->bd_disk = disk;
87192a2a 1596 bdev->bd_queue = disk->queue;
1da177e4 1597 bdev->bd_contains = bdev;
c2ee070f 1598 bdev->bd_partno = partno;
03cdadb0 1599
cf771cb5 1600 if (!partno) {
89f97496
TH
1601 ret = -ENXIO;
1602 bdev->bd_part = disk_get_part(disk, partno);
1603 if (!bdev->bd_part)
1604 goto out_clear;
1605
1196f8b8 1606 ret = 0;
1da177e4 1607 if (disk->fops->open) {
572c4892 1608 ret = disk->fops->open(bdev, mode);
d3374825
N
1609 if (ret == -ERESTARTSYS) {
1610 /* Lost a race with 'disk' being
1611 * deleted, try again.
1612 * See md.c
1613 */
1614 disk_put_part(bdev->bd_part);
1615 bdev->bd_part = NULL;
d3374825 1616 bdev->bd_disk = NULL;
87192a2a 1617 bdev->bd_queue = NULL;
d3374825 1618 mutex_unlock(&bdev->bd_mutex);
69e02c59 1619 disk_unblock_events(disk);
9df6c299 1620 put_disk_and_module(disk);
d3374825
N
1621 goto restart;
1622 }
1da177e4 1623 }
7e69723f 1624
04906b2f 1625 if (!ret) {
7e69723f 1626 bd_set_size(bdev,(loff_t)get_capacity(disk)<<9);
04906b2f
JK
1627 set_init_blocksize(bdev);
1628 }
7e69723f 1629
1196f8b8
TH
1630 /*
1631 * If the device is invalidated, rescan partition
1632 * if open succeeded or failed with -ENOMEDIUM.
1633 * The latter is necessary to prevent ghost
1634 * partitions on a removed medium.
1635 */
fe316bf2
JN
1636 if (bdev->bd_invalidated) {
1637 if (!ret)
1638 rescan_partitions(disk, bdev);
1639 else if (ret == -ENOMEDIUM)
1640 invalidate_partitions(disk, bdev);
1641 }
5a023cdb 1642
1196f8b8
TH
1643 if (ret)
1644 goto out_clear;
1da177e4 1645 } else {
1da177e4
LT
1646 struct block_device *whole;
1647 whole = bdget_disk(disk, 0);
1648 ret = -ENOMEM;
1649 if (!whole)
0762b8bd 1650 goto out_clear;
37be4124 1651 BUG_ON(for_part);
572c4892 1652 ret = __blkdev_get(whole, mode, 1);
1da177e4 1653 if (ret)
0762b8bd 1654 goto out_clear;
1da177e4 1655 bdev->bd_contains = whole;
89f97496 1656 bdev->bd_part = disk_get_part(disk, partno);
e71bf0d0 1657 if (!(disk->flags & GENHD_FL_UP) ||
89f97496 1658 !bdev->bd_part || !bdev->bd_part->nr_sects) {
1da177e4 1659 ret = -ENXIO;
0762b8bd 1660 goto out_clear;
1da177e4 1661 }
89f97496 1662 bd_set_size(bdev, (loff_t)bdev->bd_part->nr_sects << 9);
04906b2f 1663 set_init_blocksize(bdev);
1da177e4 1664 }
03e26279
JK
1665
1666 if (bdev->bd_bdi == &noop_backing_dev_info)
1667 bdev->bd_bdi = bdi_get(disk->queue->backing_dev_info);
1da177e4 1668 } else {
1da177e4 1669 if (bdev->bd_contains == bdev) {
1196f8b8
TH
1670 ret = 0;
1671 if (bdev->bd_disk->fops->open)
572c4892 1672 ret = bdev->bd_disk->fops->open(bdev, mode);
1196f8b8 1673 /* the same as first opener case, read comment there */
fe316bf2
JN
1674 if (bdev->bd_invalidated) {
1675 if (!ret)
1676 rescan_partitions(bdev->bd_disk, bdev);
1677 else if (ret == -ENOMEDIUM)
1678 invalidate_partitions(bdev->bd_disk, bdev);
1679 }
1196f8b8
TH
1680 if (ret)
1681 goto out_unlock_bdev;
1da177e4
LT
1682 }
1683 }
1684 bdev->bd_openers++;
37be4124
N
1685 if (for_part)
1686 bdev->bd_part_count++;
c039e313 1687 mutex_unlock(&bdev->bd_mutex);
69e02c59 1688 disk_unblock_events(disk);
89736653
JK
1689 /* only one opener holds refs to the module and disk */
1690 if (!first_open)
1691 put_disk_and_module(disk);
1da177e4
LT
1692 return 0;
1693
0762b8bd 1694 out_clear:
89f97496 1695 disk_put_part(bdev->bd_part);
1da177e4 1696 bdev->bd_disk = NULL;
0762b8bd 1697 bdev->bd_part = NULL;
87192a2a 1698 bdev->bd_queue = NULL;
1da177e4 1699 if (bdev != bdev->bd_contains)
572c4892 1700 __blkdev_put(bdev->bd_contains, mode, 1);
1da177e4 1701 bdev->bd_contains = NULL;
0762b8bd 1702 out_unlock_bdev:
c039e313 1703 mutex_unlock(&bdev->bd_mutex);
69e02c59 1704 disk_unblock_events(disk);
9df6c299 1705 put_disk_and_module(disk);
4345caba 1706 out:
0762b8bd
TH
1707 bdput(bdev);
1708
1da177e4
LT
1709 return ret;
1710}
1711
d4d77629
TH
1712/**
1713 * blkdev_get - open a block device
1714 * @bdev: block_device to open
1715 * @mode: FMODE_* mask
1716 * @holder: exclusive holder identifier
1717 *
1718 * Open @bdev with @mode. If @mode includes %FMODE_EXCL, @bdev is
1719 * open with exclusive access. Specifying %FMODE_EXCL with %NULL
1720 * @holder is invalid. Exclusive opens may nest for the same @holder.
1721 *
1722 * On success, the reference count of @bdev is unchanged. On failure,
1723 * @bdev is put.
1724 *
1725 * CONTEXT:
1726 * Might sleep.
1727 *
1728 * RETURNS:
1729 * 0 on success, -errno on failure.
1730 */
e525fd89 1731int blkdev_get(struct block_device *bdev, fmode_t mode, void *holder)
1da177e4 1732{
e525fd89
TH
1733 struct block_device *whole = NULL;
1734 int res;
1735
1736 WARN_ON_ONCE((mode & FMODE_EXCL) && !holder);
1737
1738 if ((mode & FMODE_EXCL) && holder) {
1739 whole = bd_start_claiming(bdev, holder);
1740 if (IS_ERR(whole)) {
1741 bdput(bdev);
1742 return PTR_ERR(whole);
1743 }
1744 }
1745
1746 res = __blkdev_get(bdev, mode, 0);
1747
1748 if (whole) {
d4dc210f
TH
1749 struct gendisk *disk = whole->bd_disk;
1750
6a027eff 1751 /* finish claiming */
77ea887e 1752 mutex_lock(&bdev->bd_mutex);
e91455ba
JK
1753 if (!res)
1754 bd_finish_claiming(bdev, whole, holder);
1755 else
1756 bd_abort_claiming(bdev, whole, holder);
77ea887e 1757 /*
d4dc210f
TH
1758 * Block event polling for write claims if requested. Any
1759 * write holder makes the write_holder state stick until
1760 * all are released. This is good enough and tracking
1761 * individual writeable reference is too fragile given the
1762 * way @mode is used in blkdev_get/put().
77ea887e 1763 */
4c49ff3f
TH
1764 if (!res && (mode & FMODE_WRITE) && !bdev->bd_write_holder &&
1765 (disk->flags & GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE)) {
77ea887e 1766 bdev->bd_write_holder = true;
d4dc210f 1767 disk_block_events(disk);
77ea887e
TH
1768 }
1769
1770 mutex_unlock(&bdev->bd_mutex);
6a027eff 1771 bdput(whole);
e525fd89
TH
1772 }
1773
1774 return res;
37be4124 1775}
1da177e4
LT
1776EXPORT_SYMBOL(blkdev_get);
1777
d4d77629
TH
1778/**
1779 * blkdev_get_by_path - open a block device by name
1780 * @path: path to the block device to open
1781 * @mode: FMODE_* mask
1782 * @holder: exclusive holder identifier
1783 *
1784 * Open the blockdevice described by the device file at @path. @mode
1785 * and @holder are identical to blkdev_get().
1786 *
1787 * On success, the returned block_device has reference count of one.
1788 *
1789 * CONTEXT:
1790 * Might sleep.
1791 *
1792 * RETURNS:
1793 * Pointer to block_device on success, ERR_PTR(-errno) on failure.
1794 */
1795struct block_device *blkdev_get_by_path(const char *path, fmode_t mode,
1796 void *holder)
1797{
1798 struct block_device *bdev;
1799 int err;
1800
1801 bdev = lookup_bdev(path);
1802 if (IS_ERR(bdev))
1803 return bdev;
1804
1805 err = blkdev_get(bdev, mode, holder);
1806 if (err)
1807 return ERR_PTR(err);
1808
e51900f7
CE
1809 if ((mode & FMODE_WRITE) && bdev_read_only(bdev)) {
1810 blkdev_put(bdev, mode);
1811 return ERR_PTR(-EACCES);
1812 }
1813
d4d77629
TH
1814 return bdev;
1815}
1816EXPORT_SYMBOL(blkdev_get_by_path);
1817
1818/**
1819 * blkdev_get_by_dev - open a block device by device number
1820 * @dev: device number of block device to open
1821 * @mode: FMODE_* mask
1822 * @holder: exclusive holder identifier
1823 *
1824 * Open the blockdevice described by device number @dev. @mode and
1825 * @holder are identical to blkdev_get().
1826 *
1827 * Use it ONLY if you really do not have anything better - i.e. when
1828 * you are behind a truly sucky interface and all you are given is a
1829 * device number. _Never_ to be used for internal purposes. If you
1830 * ever need it - reconsider your API.
1831 *
1832 * On success, the returned block_device has reference count of one.
1833 *
1834 * CONTEXT:
1835 * Might sleep.
1836 *
1837 * RETURNS:
1838 * Pointer to block_device on success, ERR_PTR(-errno) on failure.
1839 */
1840struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode, void *holder)
1841{
1842 struct block_device *bdev;
1843 int err;
1844
1845 bdev = bdget(dev);
1846 if (!bdev)
1847 return ERR_PTR(-ENOMEM);
1848
1849 err = blkdev_get(bdev, mode, holder);
1850 if (err)
1851 return ERR_PTR(err);
1852
1853 return bdev;
1854}
1855EXPORT_SYMBOL(blkdev_get_by_dev);
1856
1da177e4
LT
1857static int blkdev_open(struct inode * inode, struct file * filp)
1858{
1859 struct block_device *bdev;
1da177e4
LT
1860
1861 /*
1862 * Preserve backwards compatibility and allow large file access
1863 * even if userspace doesn't ask for it explicitly. Some mkfs
1864 * binary needs it. We might want to drop this workaround
1865 * during an unstable branch.
1866 */
1867 filp->f_flags |= O_LARGEFILE;
1868
c35fc7a5
CH
1869 filp->f_mode |= FMODE_NOWAIT;
1870
572c4892
AV
1871 if (filp->f_flags & O_NDELAY)
1872 filp->f_mode |= FMODE_NDELAY;
1873 if (filp->f_flags & O_EXCL)
1874 filp->f_mode |= FMODE_EXCL;
1875 if ((filp->f_flags & O_ACCMODE) == 3)
1876 filp->f_mode |= FMODE_WRITE_IOCTL;
1877
1da177e4 1878 bdev = bd_acquire(inode);
6a2aae06
PE
1879 if (bdev == NULL)
1880 return -ENOMEM;
1da177e4 1881
572c4892 1882 filp->f_mapping = bdev->bd_inode->i_mapping;
5660e13d 1883 filp->f_wb_err = filemap_sample_wb_err(filp->f_mapping);
572c4892 1884
e525fd89 1885 return blkdev_get(bdev, filp->f_mode, filp);
1da177e4
LT
1886}
1887
4385bab1 1888static void __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part)
2e7b651d 1889{
2e7b651d 1890 struct gendisk *disk = bdev->bd_disk;
37be4124 1891 struct block_device *victim = NULL;
2e7b651d 1892
6796bf54 1893 mutex_lock_nested(&bdev->bd_mutex, for_part);
37be4124
N
1894 if (for_part)
1895 bdev->bd_part_count--;
1896
2e7b651d 1897 if (!--bdev->bd_openers) {
6a027eff 1898 WARN_ON_ONCE(bdev->bd_holders);
2e7b651d
PZ
1899 sync_blockdev(bdev);
1900 kill_bdev(bdev);
43d1c0eb
ID
1901
1902 bdev_write_inode(bdev);
2e7b651d
PZ
1903 }
1904 if (bdev->bd_contains == bdev) {
1905 if (disk->fops->release)
db2a144b 1906 disk->fops->release(disk, mode);
2e7b651d
PZ
1907 }
1908 if (!bdev->bd_openers) {
0762b8bd
TH
1909 disk_put_part(bdev->bd_part);
1910 bdev->bd_part = NULL;
2e7b651d 1911 bdev->bd_disk = NULL;
37be4124
N
1912 if (bdev != bdev->bd_contains)
1913 victim = bdev->bd_contains;
2e7b651d 1914 bdev->bd_contains = NULL;
523e1d39 1915
9df6c299 1916 put_disk_and_module(disk);
2e7b651d 1917 }
2e7b651d
PZ
1918 mutex_unlock(&bdev->bd_mutex);
1919 bdput(bdev);
37be4124 1920 if (victim)
9a1c3542 1921 __blkdev_put(victim, mode, 1);
2e7b651d
PZ
1922}
1923
4385bab1 1924void blkdev_put(struct block_device *bdev, fmode_t mode)
37be4124 1925{
85ef06d1
TH
1926 mutex_lock(&bdev->bd_mutex);
1927
e525fd89 1928 if (mode & FMODE_EXCL) {
6a027eff
TH
1929 bool bdev_free;
1930
1931 /*
1932 * Release a claim on the device. The holder fields
1933 * are protected with bdev_lock. bd_mutex is to
1934 * synchronize disk_holder unlinking.
1935 */
6a027eff
TH
1936 spin_lock(&bdev_lock);
1937
1938 WARN_ON_ONCE(--bdev->bd_holders < 0);
1939 WARN_ON_ONCE(--bdev->bd_contains->bd_holders < 0);
1940
1941 /* bd_contains might point to self, check in a separate step */
1942 if ((bdev_free = !bdev->bd_holders))
1943 bdev->bd_holder = NULL;
1944 if (!bdev->bd_contains->bd_holders)
1945 bdev->bd_contains->bd_holder = NULL;
1946
1947 spin_unlock(&bdev_lock);
1948
77ea887e
TH
1949 /*
1950 * If this was the last claim, remove holder link and
1951 * unblock evpoll if it was a write holder.
1952 */
85ef06d1
TH
1953 if (bdev_free && bdev->bd_write_holder) {
1954 disk_unblock_events(bdev->bd_disk);
1955 bdev->bd_write_holder = false;
77ea887e 1956 }
6936217c 1957 }
77ea887e 1958
85ef06d1
TH
1959 /*
1960 * Trigger event checking and tell drivers to flush MEDIA_CHANGE
1961 * event. This is to ensure detection of media removal commanded
1962 * from userland - e.g. eject(1).
1963 */
1964 disk_flush_events(bdev->bd_disk, DISK_EVENT_MEDIA_CHANGE);
1965
1966 mutex_unlock(&bdev->bd_mutex);
1967
4385bab1 1968 __blkdev_put(bdev, mode, 0);
37be4124 1969}
2e7b651d
PZ
1970EXPORT_SYMBOL(blkdev_put);
1971
1da177e4
LT
1972static int blkdev_close(struct inode * inode, struct file * filp)
1973{
4ebb16ca 1974 struct block_device *bdev = I_BDEV(bdev_file_inode(filp));
4385bab1
AV
1975 blkdev_put(bdev, filp->f_mode);
1976 return 0;
1da177e4
LT
1977}
1978
bb93e3a5 1979static long block_ioctl(struct file *file, unsigned cmd, unsigned long arg)
1da177e4 1980{
4ebb16ca 1981 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
56b26add 1982 fmode_t mode = file->f_mode;
fd4ce1ac
CH
1983
1984 /*
1985 * O_NDELAY can be altered using fcntl(.., F_SETFL, ..), so we have
1986 * to updated it before every ioctl.
1987 */
56b26add 1988 if (file->f_flags & O_NDELAY)
fd4ce1ac
CH
1989 mode |= FMODE_NDELAY;
1990 else
1991 mode &= ~FMODE_NDELAY;
1992
56b26add 1993 return blkdev_ioctl(bdev, mode, cmd, arg);
1da177e4
LT
1994}
1995
eef99380
CH
1996/*
1997 * Write data to the block device. Only intended for the block device itself
1998 * and the raw driver which basically is a fake block device.
1999 *
2000 * Does not take i_mutex for the write and thus is not for general purpose
2001 * use.
2002 */
1456c0a8 2003ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
eef99380
CH
2004{
2005 struct file *file = iocb->ki_filp;
4ebb16ca 2006 struct inode *bd_inode = bdev_file_inode(file);
7ec7b94a 2007 loff_t size = i_size_read(bd_inode);
53362a05 2008 struct blk_plug plug;
eef99380 2009 ssize_t ret;
5f380c7f 2010
7ec7b94a
AV
2011 if (bdev_read_only(I_BDEV(bd_inode)))
2012 return -EPERM;
5f380c7f 2013
7ec7b94a 2014 if (!iov_iter_count(from))
5f380c7f
AV
2015 return 0;
2016
7ec7b94a
AV
2017 if (iocb->ki_pos >= size)
2018 return -ENOSPC;
2019
c35fc7a5
CH
2020 if ((iocb->ki_flags & (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT)
2021 return -EOPNOTSUPP;
2022
7ec7b94a 2023 iov_iter_truncate(from, size - iocb->ki_pos);
eef99380 2024
53362a05 2025 blk_start_plug(&plug);
1456c0a8 2026 ret = __generic_file_write_iter(iocb, from);
e2592217
CH
2027 if (ret > 0)
2028 ret = generic_write_sync(iocb, ret);
53362a05 2029 blk_finish_plug(&plug);
eef99380
CH
2030 return ret;
2031}
1456c0a8 2032EXPORT_SYMBOL_GPL(blkdev_write_iter);
eef99380 2033
b2de525f 2034ssize_t blkdev_read_iter(struct kiocb *iocb, struct iov_iter *to)
684c9aae
LT
2035{
2036 struct file *file = iocb->ki_filp;
4ebb16ca 2037 struct inode *bd_inode = bdev_file_inode(file);
684c9aae 2038 loff_t size = i_size_read(bd_inode);
a886038b 2039 loff_t pos = iocb->ki_pos;
684c9aae
LT
2040
2041 if (pos >= size)
2042 return 0;
2043
2044 size -= pos;
a886038b
AV
2045 iov_iter_truncate(to, size);
2046 return generic_file_read_iter(iocb, to);
684c9aae 2047}
b2de525f 2048EXPORT_SYMBOL_GPL(blkdev_read_iter);
684c9aae 2049
87d8fe1e
TT
2050/*
2051 * Try to release a page associated with block device when the system
2052 * is under memory pressure.
2053 */
2054static int blkdev_releasepage(struct page *page, gfp_t wait)
2055{
2056 struct super_block *super = BDEV_I(page->mapping->host)->bdev.bd_super;
2057
2058 if (super && super->s_op->bdev_try_to_free_page)
2059 return super->s_op->bdev_try_to_free_page(super, page, wait);
2060
2061 return try_to_free_buffers(page);
2062}
2063
7f6d5b52
RZ
2064static int blkdev_writepages(struct address_space *mapping,
2065 struct writeback_control *wbc)
2066{
7f6d5b52
RZ
2067 return generic_writepages(mapping, wbc);
2068}
2069
4c54ac62 2070static const struct address_space_operations def_blk_aops = {
1da177e4 2071 .readpage = blkdev_readpage,
447f05bb 2072 .readpages = blkdev_readpages,
1da177e4 2073 .writepage = blkdev_writepage,
6272b5a5
NP
2074 .write_begin = blkdev_write_begin,
2075 .write_end = blkdev_write_end,
7f6d5b52 2076 .writepages = blkdev_writepages,
87d8fe1e 2077 .releasepage = blkdev_releasepage,
1da177e4 2078 .direct_IO = blkdev_direct_IO,
88dbcbb3 2079 .migratepage = buffer_migrate_page_norefs,
b4597226 2080 .is_dirty_writeback = buffer_check_dirty_writeback,
1da177e4
LT
2081};
2082
25f4c414
DW
2083#define BLKDEV_FALLOC_FL_SUPPORTED \
2084 (FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE | \
2085 FALLOC_FL_ZERO_RANGE | FALLOC_FL_NO_HIDE_STALE)
2086
2087static long blkdev_fallocate(struct file *file, int mode, loff_t start,
2088 loff_t len)
2089{
2090 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
25f4c414
DW
2091 struct address_space *mapping;
2092 loff_t end = start + len - 1;
2093 loff_t isize;
2094 int error;
2095
2096 /* Fail if we don't recognize the flags. */
2097 if (mode & ~BLKDEV_FALLOC_FL_SUPPORTED)
2098 return -EOPNOTSUPP;
2099
2100 /* Don't go off the end of the device. */
2101 isize = i_size_read(bdev->bd_inode);
2102 if (start >= isize)
2103 return -EINVAL;
2104 if (end >= isize) {
2105 if (mode & FALLOC_FL_KEEP_SIZE) {
2106 len = isize - start;
2107 end = start + len - 1;
2108 } else
2109 return -EINVAL;
2110 }
2111
2112 /*
2113 * Don't allow IO that isn't aligned to logical block size.
2114 */
2115 if ((start | len) & (bdev_logical_block_size(bdev) - 1))
2116 return -EINVAL;
2117
2118 /* Invalidate the page cache, including dirty pages. */
2119 mapping = bdev->bd_inode->i_mapping;
2120 truncate_inode_pages_range(mapping, start, end);
2121
2122 switch (mode) {
2123 case FALLOC_FL_ZERO_RANGE:
2124 case FALLOC_FL_ZERO_RANGE | FALLOC_FL_KEEP_SIZE:
2125 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
ee472d83 2126 GFP_KERNEL, BLKDEV_ZERO_NOUNMAP);
25f4c414
DW
2127 break;
2128 case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE:
34045129
CH
2129 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
2130 GFP_KERNEL, BLKDEV_ZERO_NOFALLBACK);
25f4c414
DW
2131 break;
2132 case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE | FALLOC_FL_NO_HIDE_STALE:
25f4c414
DW
2133 error = blkdev_issue_discard(bdev, start >> 9, len >> 9,
2134 GFP_KERNEL, 0);
2135 break;
2136 default:
2137 return -EOPNOTSUPP;
2138 }
2139 if (error)
2140 return error;
2141
2142 /*
2143 * Invalidate again; if someone wandered in and dirtied a page,
2144 * the caller will be given -EBUSY. The third argument is
2145 * inclusive, so the rounding here is safe.
2146 */
2147 return invalidate_inode_pages2_range(mapping,
2148 start >> PAGE_SHIFT,
2149 end >> PAGE_SHIFT);
2150}
2151
4b6f5d20 2152const struct file_operations def_blk_fops = {
1da177e4
LT
2153 .open = blkdev_open,
2154 .release = blkdev_close,
2155 .llseek = block_llseek,
a886038b 2156 .read_iter = blkdev_read_iter,
1456c0a8 2157 .write_iter = blkdev_write_iter,
eae83ce1 2158 .iopoll = blkdev_iopoll,
acc93d30 2159 .mmap = generic_file_mmap,
b1dd3b28 2160 .fsync = blkdev_fsync,
bb93e3a5 2161 .unlocked_ioctl = block_ioctl,
1da177e4
LT
2162#ifdef CONFIG_COMPAT
2163 .compat_ioctl = compat_blkdev_ioctl,
2164#endif
1e8b3332 2165 .splice_read = generic_file_splice_read,
8d020765 2166 .splice_write = iter_file_splice_write,
25f4c414 2167 .fallocate = blkdev_fallocate,
1da177e4
LT
2168};
2169
2170int ioctl_by_bdev(struct block_device *bdev, unsigned cmd, unsigned long arg)
2171{
2172 int res;
2173 mm_segment_t old_fs = get_fs();
2174 set_fs(KERNEL_DS);
56b26add 2175 res = blkdev_ioctl(bdev, 0, cmd, arg);
1da177e4
LT
2176 set_fs(old_fs);
2177 return res;
2178}
2179
2180EXPORT_SYMBOL(ioctl_by_bdev);
2181
2182/**
2183 * lookup_bdev - lookup a struct block_device by name
94e2959e 2184 * @pathname: special file representing the block device
1da177e4 2185 *
57d1b536 2186 * Get a reference to the blockdevice at @pathname in the current
1da177e4
LT
2187 * namespace if possible and return it. Return ERR_PTR(error)
2188 * otherwise.
2189 */
421748ec 2190struct block_device *lookup_bdev(const char *pathname)
1da177e4
LT
2191{
2192 struct block_device *bdev;
2193 struct inode *inode;
421748ec 2194 struct path path;
1da177e4
LT
2195 int error;
2196
421748ec 2197 if (!pathname || !*pathname)
1da177e4
LT
2198 return ERR_PTR(-EINVAL);
2199
421748ec 2200 error = kern_path(pathname, LOOKUP_FOLLOW, &path);
1da177e4
LT
2201 if (error)
2202 return ERR_PTR(error);
2203
bb668734 2204 inode = d_backing_inode(path.dentry);
1da177e4
LT
2205 error = -ENOTBLK;
2206 if (!S_ISBLK(inode->i_mode))
2207 goto fail;
2208 error = -EACCES;
a2982cc9 2209 if (!may_open_dev(&path))
1da177e4
LT
2210 goto fail;
2211 error = -ENOMEM;
2212 bdev = bd_acquire(inode);
2213 if (!bdev)
2214 goto fail;
2215out:
421748ec 2216 path_put(&path);
1da177e4
LT
2217 return bdev;
2218fail:
2219 bdev = ERR_PTR(error);
2220 goto out;
2221}
d5686b44 2222EXPORT_SYMBOL(lookup_bdev);
1da177e4 2223
93b270f7 2224int __invalidate_device(struct block_device *bdev, bool kill_dirty)
b71e8a4c
DH
2225{
2226 struct super_block *sb = get_super(bdev);
2227 int res = 0;
2228
2229 if (sb) {
2230 /*
2231 * no need to lock the super, get_super holds the
2232 * read mutex so the filesystem cannot go away
2233 * under us (->put_super runs with the write lock
2234 * hold).
2235 */
2236 shrink_dcache_sb(sb);
93b270f7 2237 res = invalidate_inodes(sb, kill_dirty);
b71e8a4c
DH
2238 drop_super(sb);
2239 }
f98393a6 2240 invalidate_bdev(bdev);
b71e8a4c
DH
2241 return res;
2242}
2243EXPORT_SYMBOL(__invalidate_device);
5c0d6b60
JK
2244
2245void iterate_bdevs(void (*func)(struct block_device *, void *), void *arg)
2246{
2247 struct inode *inode, *old_inode = NULL;
2248
74278da9 2249 spin_lock(&blockdev_superblock->s_inode_list_lock);
5c0d6b60
JK
2250 list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list) {
2251 struct address_space *mapping = inode->i_mapping;
af309226 2252 struct block_device *bdev;
5c0d6b60
JK
2253
2254 spin_lock(&inode->i_lock);
2255 if (inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW) ||
2256 mapping->nrpages == 0) {
2257 spin_unlock(&inode->i_lock);
2258 continue;
2259 }
2260 __iget(inode);
2261 spin_unlock(&inode->i_lock);
74278da9 2262 spin_unlock(&blockdev_superblock->s_inode_list_lock);
5c0d6b60
JK
2263 /*
2264 * We hold a reference to 'inode' so it couldn't have been
2265 * removed from s_inodes list while we dropped the
74278da9 2266 * s_inode_list_lock We cannot iput the inode now as we can
5c0d6b60 2267 * be holding the last reference and we cannot iput it under
74278da9 2268 * s_inode_list_lock. So we keep the reference and iput it
5c0d6b60
JK
2269 * later.
2270 */
2271 iput(old_inode);
2272 old_inode = inode;
af309226 2273 bdev = I_BDEV(inode);
5c0d6b60 2274
af309226
RV
2275 mutex_lock(&bdev->bd_mutex);
2276 if (bdev->bd_openers)
2277 func(bdev, arg);
2278 mutex_unlock(&bdev->bd_mutex);
5c0d6b60 2279
74278da9 2280 spin_lock(&blockdev_superblock->s_inode_list_lock);
5c0d6b60 2281 }
74278da9 2282 spin_unlock(&blockdev_superblock->s_inode_list_lock);
5c0d6b60
JK
2283 iput(old_inode);
2284}