]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blob - fs/block_dev.c
Merge tag 'livepatching-for-5.15' of git://git.kernel.org/pub/scm/linux/kernel/git...
[mirror_ubuntu-jammy-kernel.git] / fs / block_dev.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Copyright (C) 1991, 1992 Linus Torvalds
4 * Copyright (C) 2001 Andrea Arcangeli <andrea@suse.de> SuSE
5 * Copyright (C) 2016 - 2020 Christoph Hellwig
6 */
7
8 #include <linux/init.h>
9 #include <linux/mm.h>
10 #include <linux/fcntl.h>
11 #include <linux/slab.h>
12 #include <linux/kmod.h>
13 #include <linux/major.h>
14 #include <linux/device_cgroup.h>
15 #include <linux/highmem.h>
16 #include <linux/blkdev.h>
17 #include <linux/backing-dev.h>
18 #include <linux/module.h>
19 #include <linux/blkpg.h>
20 #include <linux/magic.h>
21 #include <linux/buffer_head.h>
22 #include <linux/swap.h>
23 #include <linux/pagevec.h>
24 #include <linux/writeback.h>
25 #include <linux/mpage.h>
26 #include <linux/mount.h>
27 #include <linux/pseudo_fs.h>
28 #include <linux/uio.h>
29 #include <linux/namei.h>
30 #include <linux/log2.h>
31 #include <linux/cleancache.h>
32 #include <linux/task_io_accounting_ops.h>
33 #include <linux/falloc.h>
34 #include <linux/part_stat.h>
35 #include <linux/uaccess.h>
36 #include <linux/suspend.h>
37 #include "internal.h"
38 #include "../block/blk.h"
39
40 struct bdev_inode {
41 struct block_device bdev;
42 struct inode vfs_inode;
43 };
44
45 static const struct address_space_operations def_blk_aops;
46
47 static inline struct bdev_inode *BDEV_I(struct inode *inode)
48 {
49 return container_of(inode, struct bdev_inode, vfs_inode);
50 }
51
52 struct block_device *I_BDEV(struct inode *inode)
53 {
54 return &BDEV_I(inode)->bdev;
55 }
56 EXPORT_SYMBOL(I_BDEV);
57
58 static void bdev_write_inode(struct block_device *bdev)
59 {
60 struct inode *inode = bdev->bd_inode;
61 int ret;
62
63 spin_lock(&inode->i_lock);
64 while (inode->i_state & I_DIRTY) {
65 spin_unlock(&inode->i_lock);
66 ret = write_inode_now(inode, true);
67 if (ret) {
68 char name[BDEVNAME_SIZE];
69 pr_warn_ratelimited("VFS: Dirty inode writeback failed "
70 "for block device %s (err=%d).\n",
71 bdevname(bdev, name), ret);
72 }
73 spin_lock(&inode->i_lock);
74 }
75 spin_unlock(&inode->i_lock);
76 }
77
78 /* Kill _all_ buffers and pagecache , dirty or not.. */
79 static void kill_bdev(struct block_device *bdev)
80 {
81 struct address_space *mapping = bdev->bd_inode->i_mapping;
82
83 if (mapping_empty(mapping))
84 return;
85
86 invalidate_bh_lrus();
87 truncate_inode_pages(mapping, 0);
88 }
89
90 /* Invalidate clean unused buffers and pagecache. */
91 void invalidate_bdev(struct block_device *bdev)
92 {
93 struct address_space *mapping = bdev->bd_inode->i_mapping;
94
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 }
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 */
103 cleancache_invalidate_inode(mapping);
104 }
105 EXPORT_SYMBOL(invalidate_bdev);
106
107 /*
108 * Drop all buffers & page cache for given bdev range. This function bails
109 * with error if bdev has other exclusive owner (such as filesystem).
110 */
111 int truncate_bdev_range(struct block_device *bdev, fmode_t mode,
112 loff_t lstart, loff_t lend)
113 {
114 /*
115 * If we don't hold exclusive handle for the device, upgrade to it
116 * while we discard the buffer cache to avoid discarding buffers
117 * under live filesystem.
118 */
119 if (!(mode & FMODE_EXCL)) {
120 int err = bd_prepare_to_claim(bdev, truncate_bdev_range);
121 if (err)
122 goto invalidate;
123 }
124
125 truncate_inode_pages_range(bdev->bd_inode->i_mapping, lstart, lend);
126 if (!(mode & FMODE_EXCL))
127 bd_abort_claiming(bdev, truncate_bdev_range);
128 return 0;
129
130 invalidate:
131 /*
132 * Someone else has handle exclusively open. Try invalidating instead.
133 * The 'end' argument is inclusive so the rounding is safe.
134 */
135 return invalidate_inode_pages2_range(bdev->bd_inode->i_mapping,
136 lstart >> PAGE_SHIFT,
137 lend >> PAGE_SHIFT);
138 }
139
140 static void set_init_blocksize(struct block_device *bdev)
141 {
142 unsigned int bsize = bdev_logical_block_size(bdev);
143 loff_t size = i_size_read(bdev->bd_inode);
144
145 while (bsize < PAGE_SIZE) {
146 if (size & bsize)
147 break;
148 bsize <<= 1;
149 }
150 bdev->bd_inode->i_blkbits = blksize_bits(bsize);
151 }
152
153 int set_blocksize(struct block_device *bdev, int size)
154 {
155 /* Size must be a power of two, and between 512 and PAGE_SIZE */
156 if (size > PAGE_SIZE || size < 512 || !is_power_of_2(size))
157 return -EINVAL;
158
159 /* Size cannot be smaller than the size supported by the device */
160 if (size < bdev_logical_block_size(bdev))
161 return -EINVAL;
162
163 /* Don't change the size if it is same as current */
164 if (bdev->bd_inode->i_blkbits != blksize_bits(size)) {
165 sync_blockdev(bdev);
166 bdev->bd_inode->i_blkbits = blksize_bits(size);
167 kill_bdev(bdev);
168 }
169 return 0;
170 }
171
172 EXPORT_SYMBOL(set_blocksize);
173
174 int sb_set_blocksize(struct super_block *sb, int size)
175 {
176 if (set_blocksize(sb->s_bdev, size))
177 return 0;
178 /* If we get here, we know size is power of two
179 * and it's value is between 512 and PAGE_SIZE */
180 sb->s_blocksize = size;
181 sb->s_blocksize_bits = blksize_bits(size);
182 return sb->s_blocksize;
183 }
184
185 EXPORT_SYMBOL(sb_set_blocksize);
186
187 int sb_min_blocksize(struct super_block *sb, int size)
188 {
189 int minsize = bdev_logical_block_size(sb->s_bdev);
190 if (size < minsize)
191 size = minsize;
192 return sb_set_blocksize(sb, size);
193 }
194
195 EXPORT_SYMBOL(sb_min_blocksize);
196
197 static int
198 blkdev_get_block(struct inode *inode, sector_t iblock,
199 struct buffer_head *bh, int create)
200 {
201 bh->b_bdev = I_BDEV(inode);
202 bh->b_blocknr = iblock;
203 set_buffer_mapped(bh);
204 return 0;
205 }
206
207 static struct inode *bdev_file_inode(struct file *file)
208 {
209 return file->f_mapping->host;
210 }
211
212 static unsigned int dio_bio_write_op(struct kiocb *iocb)
213 {
214 unsigned int op = REQ_OP_WRITE | REQ_SYNC | REQ_IDLE;
215
216 /* avoid the need for a I/O completion work item */
217 if (iocb->ki_flags & IOCB_DSYNC)
218 op |= REQ_FUA;
219 return op;
220 }
221
222 #define DIO_INLINE_BIO_VECS 4
223
224 static void blkdev_bio_end_io_simple(struct bio *bio)
225 {
226 struct task_struct *waiter = bio->bi_private;
227
228 WRITE_ONCE(bio->bi_private, NULL);
229 blk_wake_io_task(waiter);
230 }
231
232 static ssize_t
233 __blkdev_direct_IO_simple(struct kiocb *iocb, struct iov_iter *iter,
234 unsigned int nr_pages)
235 {
236 struct file *file = iocb->ki_filp;
237 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
238 struct bio_vec inline_vecs[DIO_INLINE_BIO_VECS], *vecs;
239 loff_t pos = iocb->ki_pos;
240 bool should_dirty = false;
241 struct bio bio;
242 ssize_t ret;
243 blk_qc_t qc;
244
245 if ((pos | iov_iter_alignment(iter)) &
246 (bdev_logical_block_size(bdev) - 1))
247 return -EINVAL;
248
249 if (nr_pages <= DIO_INLINE_BIO_VECS)
250 vecs = inline_vecs;
251 else {
252 vecs = kmalloc_array(nr_pages, sizeof(struct bio_vec),
253 GFP_KERNEL);
254 if (!vecs)
255 return -ENOMEM;
256 }
257
258 bio_init(&bio, vecs, nr_pages);
259 bio_set_dev(&bio, bdev);
260 bio.bi_iter.bi_sector = pos >> 9;
261 bio.bi_write_hint = iocb->ki_hint;
262 bio.bi_private = current;
263 bio.bi_end_io = blkdev_bio_end_io_simple;
264 bio.bi_ioprio = iocb->ki_ioprio;
265
266 ret = bio_iov_iter_get_pages(&bio, iter);
267 if (unlikely(ret))
268 goto out;
269 ret = bio.bi_iter.bi_size;
270
271 if (iov_iter_rw(iter) == READ) {
272 bio.bi_opf = REQ_OP_READ;
273 if (iter_is_iovec(iter))
274 should_dirty = true;
275 } else {
276 bio.bi_opf = dio_bio_write_op(iocb);
277 task_io_account_write(ret);
278 }
279 if (iocb->ki_flags & IOCB_NOWAIT)
280 bio.bi_opf |= REQ_NOWAIT;
281 if (iocb->ki_flags & IOCB_HIPRI)
282 bio_set_polled(&bio, iocb);
283
284 qc = submit_bio(&bio);
285 for (;;) {
286 set_current_state(TASK_UNINTERRUPTIBLE);
287 if (!READ_ONCE(bio.bi_private))
288 break;
289 if (!(iocb->ki_flags & IOCB_HIPRI) ||
290 !blk_poll(bdev_get_queue(bdev), qc, true))
291 blk_io_schedule();
292 }
293 __set_current_state(TASK_RUNNING);
294
295 bio_release_pages(&bio, should_dirty);
296 if (unlikely(bio.bi_status))
297 ret = blk_status_to_errno(bio.bi_status);
298
299 out:
300 if (vecs != inline_vecs)
301 kfree(vecs);
302
303 bio_uninit(&bio);
304
305 return ret;
306 }
307
308 struct blkdev_dio {
309 union {
310 struct kiocb *iocb;
311 struct task_struct *waiter;
312 };
313 size_t size;
314 atomic_t ref;
315 bool multi_bio : 1;
316 bool should_dirty : 1;
317 bool is_sync : 1;
318 struct bio bio;
319 };
320
321 static struct bio_set blkdev_dio_pool;
322
323 static int blkdev_iopoll(struct kiocb *kiocb, bool wait)
324 {
325 struct block_device *bdev = I_BDEV(kiocb->ki_filp->f_mapping->host);
326 struct request_queue *q = bdev_get_queue(bdev);
327
328 return blk_poll(q, READ_ONCE(kiocb->ki_cookie), wait);
329 }
330
331 static void blkdev_bio_end_io(struct bio *bio)
332 {
333 struct blkdev_dio *dio = bio->bi_private;
334 bool should_dirty = dio->should_dirty;
335
336 if (bio->bi_status && !dio->bio.bi_status)
337 dio->bio.bi_status = bio->bi_status;
338
339 if (!dio->multi_bio || atomic_dec_and_test(&dio->ref)) {
340 if (!dio->is_sync) {
341 struct kiocb *iocb = dio->iocb;
342 ssize_t ret;
343
344 if (likely(!dio->bio.bi_status)) {
345 ret = dio->size;
346 iocb->ki_pos += ret;
347 } else {
348 ret = blk_status_to_errno(dio->bio.bi_status);
349 }
350
351 dio->iocb->ki_complete(iocb, ret, 0);
352 if (dio->multi_bio)
353 bio_put(&dio->bio);
354 } else {
355 struct task_struct *waiter = dio->waiter;
356
357 WRITE_ONCE(dio->waiter, NULL);
358 blk_wake_io_task(waiter);
359 }
360 }
361
362 if (should_dirty) {
363 bio_check_pages_dirty(bio);
364 } else {
365 bio_release_pages(bio, false);
366 bio_put(bio);
367 }
368 }
369
370 static ssize_t __blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
371 unsigned int nr_pages)
372 {
373 struct file *file = iocb->ki_filp;
374 struct inode *inode = bdev_file_inode(file);
375 struct block_device *bdev = I_BDEV(inode);
376 struct blk_plug plug;
377 struct blkdev_dio *dio;
378 struct bio *bio;
379 bool is_poll = (iocb->ki_flags & IOCB_HIPRI) != 0;
380 bool is_read = (iov_iter_rw(iter) == READ), is_sync;
381 loff_t pos = iocb->ki_pos;
382 blk_qc_t qc = BLK_QC_T_NONE;
383 int ret = 0;
384
385 if ((pos | iov_iter_alignment(iter)) &
386 (bdev_logical_block_size(bdev) - 1))
387 return -EINVAL;
388
389 bio = bio_alloc_kiocb(iocb, nr_pages, &blkdev_dio_pool);
390
391 dio = container_of(bio, struct blkdev_dio, bio);
392 dio->is_sync = is_sync = is_sync_kiocb(iocb);
393 if (dio->is_sync) {
394 dio->waiter = current;
395 bio_get(bio);
396 } else {
397 dio->iocb = iocb;
398 }
399
400 dio->size = 0;
401 dio->multi_bio = false;
402 dio->should_dirty = is_read && iter_is_iovec(iter);
403
404 /*
405 * Don't plug for HIPRI/polled IO, as those should go straight
406 * to issue
407 */
408 if (!is_poll)
409 blk_start_plug(&plug);
410
411 for (;;) {
412 bio_set_dev(bio, bdev);
413 bio->bi_iter.bi_sector = pos >> 9;
414 bio->bi_write_hint = iocb->ki_hint;
415 bio->bi_private = dio;
416 bio->bi_end_io = blkdev_bio_end_io;
417 bio->bi_ioprio = iocb->ki_ioprio;
418
419 ret = bio_iov_iter_get_pages(bio, iter);
420 if (unlikely(ret)) {
421 bio->bi_status = BLK_STS_IOERR;
422 bio_endio(bio);
423 break;
424 }
425
426 if (is_read) {
427 bio->bi_opf = REQ_OP_READ;
428 if (dio->should_dirty)
429 bio_set_pages_dirty(bio);
430 } else {
431 bio->bi_opf = dio_bio_write_op(iocb);
432 task_io_account_write(bio->bi_iter.bi_size);
433 }
434 if (iocb->ki_flags & IOCB_NOWAIT)
435 bio->bi_opf |= REQ_NOWAIT;
436
437 dio->size += bio->bi_iter.bi_size;
438 pos += bio->bi_iter.bi_size;
439
440 nr_pages = bio_iov_vecs_to_alloc(iter, BIO_MAX_VECS);
441 if (!nr_pages) {
442 bool polled = false;
443
444 if (iocb->ki_flags & IOCB_HIPRI) {
445 bio_set_polled(bio, iocb);
446 polled = true;
447 }
448
449 qc = submit_bio(bio);
450
451 if (polled)
452 WRITE_ONCE(iocb->ki_cookie, qc);
453 break;
454 }
455
456 if (!dio->multi_bio) {
457 /*
458 * AIO needs an extra reference to ensure the dio
459 * structure which is embedded into the first bio
460 * stays around.
461 */
462 if (!is_sync)
463 bio_get(bio);
464 dio->multi_bio = true;
465 atomic_set(&dio->ref, 2);
466 } else {
467 atomic_inc(&dio->ref);
468 }
469
470 submit_bio(bio);
471 bio = bio_alloc(GFP_KERNEL, nr_pages);
472 }
473
474 if (!is_poll)
475 blk_finish_plug(&plug);
476
477 if (!is_sync)
478 return -EIOCBQUEUED;
479
480 for (;;) {
481 set_current_state(TASK_UNINTERRUPTIBLE);
482 if (!READ_ONCE(dio->waiter))
483 break;
484
485 if (!(iocb->ki_flags & IOCB_HIPRI) ||
486 !blk_poll(bdev_get_queue(bdev), qc, true))
487 blk_io_schedule();
488 }
489 __set_current_state(TASK_RUNNING);
490
491 if (!ret)
492 ret = blk_status_to_errno(dio->bio.bi_status);
493 if (likely(!ret))
494 ret = dio->size;
495
496 bio_put(&dio->bio);
497 return ret;
498 }
499
500 static ssize_t
501 blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
502 {
503 unsigned int nr_pages;
504
505 if (!iov_iter_count(iter))
506 return 0;
507
508 nr_pages = bio_iov_vecs_to_alloc(iter, BIO_MAX_VECS + 1);
509 if (is_sync_kiocb(iocb) && nr_pages <= BIO_MAX_VECS)
510 return __blkdev_direct_IO_simple(iocb, iter, nr_pages);
511
512 return __blkdev_direct_IO(iocb, iter, bio_max_segs(nr_pages));
513 }
514
515 static __init int blkdev_init(void)
516 {
517 return bioset_init(&blkdev_dio_pool, 4,
518 offsetof(struct blkdev_dio, bio),
519 BIOSET_NEED_BVECS|BIOSET_PERCPU_CACHE);
520 }
521 module_init(blkdev_init);
522
523 int __sync_blockdev(struct block_device *bdev, int wait)
524 {
525 if (!bdev)
526 return 0;
527 if (!wait)
528 return filemap_flush(bdev->bd_inode->i_mapping);
529 return filemap_write_and_wait(bdev->bd_inode->i_mapping);
530 }
531
532 /*
533 * Write out and wait upon all the dirty data associated with a block
534 * device via its mapping. Does not take the superblock lock.
535 */
536 int sync_blockdev(struct block_device *bdev)
537 {
538 return __sync_blockdev(bdev, 1);
539 }
540 EXPORT_SYMBOL(sync_blockdev);
541
542 /*
543 * Write out and wait upon all dirty data associated with this
544 * device. Filesystem data as well as the underlying block
545 * device. Takes the superblock lock.
546 */
547 int fsync_bdev(struct block_device *bdev)
548 {
549 struct super_block *sb = get_super(bdev);
550 if (sb) {
551 int res = sync_filesystem(sb);
552 drop_super(sb);
553 return res;
554 }
555 return sync_blockdev(bdev);
556 }
557 EXPORT_SYMBOL(fsync_bdev);
558
559 /**
560 * freeze_bdev -- lock a filesystem and force it into a consistent state
561 * @bdev: blockdevice to lock
562 *
563 * If a superblock is found on this device, we take the s_umount semaphore
564 * on it to make sure nobody unmounts until the snapshot creation is done.
565 * The reference counter (bd_fsfreeze_count) guarantees that only the last
566 * unfreeze process can unfreeze the frozen filesystem actually when multiple
567 * freeze requests arrive simultaneously. It counts up in freeze_bdev() and
568 * count down in thaw_bdev(). When it becomes 0, thaw_bdev() will unfreeze
569 * actually.
570 */
571 int freeze_bdev(struct block_device *bdev)
572 {
573 struct super_block *sb;
574 int error = 0;
575
576 mutex_lock(&bdev->bd_fsfreeze_mutex);
577 if (++bdev->bd_fsfreeze_count > 1)
578 goto done;
579
580 sb = get_active_super(bdev);
581 if (!sb)
582 goto sync;
583 if (sb->s_op->freeze_super)
584 error = sb->s_op->freeze_super(sb);
585 else
586 error = freeze_super(sb);
587 deactivate_super(sb);
588
589 if (error) {
590 bdev->bd_fsfreeze_count--;
591 goto done;
592 }
593 bdev->bd_fsfreeze_sb = sb;
594
595 sync:
596 sync_blockdev(bdev);
597 done:
598 mutex_unlock(&bdev->bd_fsfreeze_mutex);
599 return error;
600 }
601 EXPORT_SYMBOL(freeze_bdev);
602
603 /**
604 * thaw_bdev -- unlock filesystem
605 * @bdev: blockdevice to unlock
606 *
607 * Unlocks the filesystem and marks it writeable again after freeze_bdev().
608 */
609 int thaw_bdev(struct block_device *bdev)
610 {
611 struct super_block *sb;
612 int error = -EINVAL;
613
614 mutex_lock(&bdev->bd_fsfreeze_mutex);
615 if (!bdev->bd_fsfreeze_count)
616 goto out;
617
618 error = 0;
619 if (--bdev->bd_fsfreeze_count > 0)
620 goto out;
621
622 sb = bdev->bd_fsfreeze_sb;
623 if (!sb)
624 goto out;
625
626 if (sb->s_op->thaw_super)
627 error = sb->s_op->thaw_super(sb);
628 else
629 error = thaw_super(sb);
630 if (error)
631 bdev->bd_fsfreeze_count++;
632 else
633 bdev->bd_fsfreeze_sb = NULL;
634 out:
635 mutex_unlock(&bdev->bd_fsfreeze_mutex);
636 return error;
637 }
638 EXPORT_SYMBOL(thaw_bdev);
639
640 static int blkdev_writepage(struct page *page, struct writeback_control *wbc)
641 {
642 return block_write_full_page(page, blkdev_get_block, wbc);
643 }
644
645 static int blkdev_readpage(struct file * file, struct page * page)
646 {
647 return block_read_full_page(page, blkdev_get_block);
648 }
649
650 static void blkdev_readahead(struct readahead_control *rac)
651 {
652 mpage_readahead(rac, blkdev_get_block);
653 }
654
655 static int blkdev_write_begin(struct file *file, struct address_space *mapping,
656 loff_t pos, unsigned len, unsigned flags,
657 struct page **pagep, void **fsdata)
658 {
659 return block_write_begin(mapping, pos, len, flags, pagep,
660 blkdev_get_block);
661 }
662
663 static int blkdev_write_end(struct file *file, struct address_space *mapping,
664 loff_t pos, unsigned len, unsigned copied,
665 struct page *page, void *fsdata)
666 {
667 int ret;
668 ret = block_write_end(file, mapping, pos, len, copied, page, fsdata);
669
670 unlock_page(page);
671 put_page(page);
672
673 return ret;
674 }
675
676 /*
677 * private llseek:
678 * for a block special file file_inode(file)->i_size is zero
679 * so we compute the size by hand (just as in block_read/write above)
680 */
681 static loff_t block_llseek(struct file *file, loff_t offset, int whence)
682 {
683 struct inode *bd_inode = bdev_file_inode(file);
684 loff_t retval;
685
686 inode_lock(bd_inode);
687 retval = fixed_size_llseek(file, offset, whence, i_size_read(bd_inode));
688 inode_unlock(bd_inode);
689 return retval;
690 }
691
692 static int blkdev_fsync(struct file *filp, loff_t start, loff_t end,
693 int datasync)
694 {
695 struct inode *bd_inode = bdev_file_inode(filp);
696 struct block_device *bdev = I_BDEV(bd_inode);
697 int error;
698
699 error = file_write_and_wait_range(filp, start, end);
700 if (error)
701 return error;
702
703 /*
704 * There is no need to serialise calls to blkdev_issue_flush with
705 * i_mutex and doing so causes performance issues with concurrent
706 * O_SYNC writers to a block device.
707 */
708 error = blkdev_issue_flush(bdev);
709 if (error == -EOPNOTSUPP)
710 error = 0;
711
712 return error;
713 }
714
715 /**
716 * bdev_read_page() - Start reading a page from a block device
717 * @bdev: The device to read the page from
718 * @sector: The offset on the device to read the page to (need not be aligned)
719 * @page: The page to read
720 *
721 * On entry, the page should be locked. It will be unlocked when the page
722 * has been read. If the block driver implements rw_page synchronously,
723 * that will be true on exit from this function, but it need not be.
724 *
725 * Errors returned by this function are usually "soft", eg out of memory, or
726 * queue full; callers should try a different route to read this page rather
727 * than propagate an error back up the stack.
728 *
729 * Return: negative errno if an error occurs, 0 if submission was successful.
730 */
731 int bdev_read_page(struct block_device *bdev, sector_t sector,
732 struct page *page)
733 {
734 const struct block_device_operations *ops = bdev->bd_disk->fops;
735 int result = -EOPNOTSUPP;
736
737 if (!ops->rw_page || bdev_get_integrity(bdev))
738 return result;
739
740 result = blk_queue_enter(bdev->bd_disk->queue, 0);
741 if (result)
742 return result;
743 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
744 REQ_OP_READ);
745 blk_queue_exit(bdev->bd_disk->queue);
746 return result;
747 }
748
749 /**
750 * bdev_write_page() - Start writing a page to a block device
751 * @bdev: The device to write the page to
752 * @sector: The offset on the device to write the page to (need not be aligned)
753 * @page: The page to write
754 * @wbc: The writeback_control for the write
755 *
756 * On entry, the page should be locked and not currently under writeback.
757 * On exit, if the write started successfully, the page will be unlocked and
758 * under writeback. If the write failed already (eg the driver failed to
759 * queue the page to the device), the page will still be locked. If the
760 * caller is a ->writepage implementation, it will need to unlock the page.
761 *
762 * Errors returned by this function are usually "soft", eg out of memory, or
763 * queue full; callers should try a different route to write this page rather
764 * than propagate an error back up the stack.
765 *
766 * Return: negative errno if an error occurs, 0 if submission was successful.
767 */
768 int bdev_write_page(struct block_device *bdev, sector_t sector,
769 struct page *page, struct writeback_control *wbc)
770 {
771 int result;
772 const struct block_device_operations *ops = bdev->bd_disk->fops;
773
774 if (!ops->rw_page || bdev_get_integrity(bdev))
775 return -EOPNOTSUPP;
776 result = blk_queue_enter(bdev->bd_disk->queue, 0);
777 if (result)
778 return result;
779
780 set_page_writeback(page);
781 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
782 REQ_OP_WRITE);
783 if (result) {
784 end_page_writeback(page);
785 } else {
786 clean_page_buffers(page);
787 unlock_page(page);
788 }
789 blk_queue_exit(bdev->bd_disk->queue);
790 return result;
791 }
792
793 /*
794 * pseudo-fs
795 */
796
797 static __cacheline_aligned_in_smp DEFINE_SPINLOCK(bdev_lock);
798 static struct kmem_cache * bdev_cachep __read_mostly;
799
800 static struct inode *bdev_alloc_inode(struct super_block *sb)
801 {
802 struct bdev_inode *ei = kmem_cache_alloc(bdev_cachep, GFP_KERNEL);
803
804 if (!ei)
805 return NULL;
806 memset(&ei->bdev, 0, sizeof(ei->bdev));
807 return &ei->vfs_inode;
808 }
809
810 static void bdev_free_inode(struct inode *inode)
811 {
812 struct block_device *bdev = I_BDEV(inode);
813
814 free_percpu(bdev->bd_stats);
815 kfree(bdev->bd_meta_info);
816
817 if (!bdev_is_partition(bdev)) {
818 if (bdev->bd_disk && bdev->bd_disk->bdi)
819 bdi_put(bdev->bd_disk->bdi);
820 kfree(bdev->bd_disk);
821 }
822
823 if (MAJOR(bdev->bd_dev) == BLOCK_EXT_MAJOR)
824 blk_free_ext_minor(MINOR(bdev->bd_dev));
825
826 kmem_cache_free(bdev_cachep, BDEV_I(inode));
827 }
828
829 static void init_once(void *data)
830 {
831 struct bdev_inode *ei = data;
832
833 inode_init_once(&ei->vfs_inode);
834 }
835
836 static void bdev_evict_inode(struct inode *inode)
837 {
838 truncate_inode_pages_final(&inode->i_data);
839 invalidate_inode_buffers(inode); /* is it needed here? */
840 clear_inode(inode);
841 }
842
843 static const struct super_operations bdev_sops = {
844 .statfs = simple_statfs,
845 .alloc_inode = bdev_alloc_inode,
846 .free_inode = bdev_free_inode,
847 .drop_inode = generic_delete_inode,
848 .evict_inode = bdev_evict_inode,
849 };
850
851 static int bd_init_fs_context(struct fs_context *fc)
852 {
853 struct pseudo_fs_context *ctx = init_pseudo(fc, BDEVFS_MAGIC);
854 if (!ctx)
855 return -ENOMEM;
856 fc->s_iflags |= SB_I_CGROUPWB;
857 ctx->ops = &bdev_sops;
858 return 0;
859 }
860
861 static struct file_system_type bd_type = {
862 .name = "bdev",
863 .init_fs_context = bd_init_fs_context,
864 .kill_sb = kill_anon_super,
865 };
866
867 struct super_block *blockdev_superblock __read_mostly;
868 EXPORT_SYMBOL_GPL(blockdev_superblock);
869
870 void __init bdev_cache_init(void)
871 {
872 int err;
873 static struct vfsmount *bd_mnt;
874
875 bdev_cachep = kmem_cache_create("bdev_cache", sizeof(struct bdev_inode),
876 0, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
877 SLAB_MEM_SPREAD|SLAB_ACCOUNT|SLAB_PANIC),
878 init_once);
879 err = register_filesystem(&bd_type);
880 if (err)
881 panic("Cannot register bdev pseudo-fs");
882 bd_mnt = kern_mount(&bd_type);
883 if (IS_ERR(bd_mnt))
884 panic("Cannot create bdev pseudo-fs");
885 blockdev_superblock = bd_mnt->mnt_sb; /* For writeback */
886 }
887
888 struct block_device *bdev_alloc(struct gendisk *disk, u8 partno)
889 {
890 struct block_device *bdev;
891 struct inode *inode;
892
893 inode = new_inode(blockdev_superblock);
894 if (!inode)
895 return NULL;
896 inode->i_mode = S_IFBLK;
897 inode->i_rdev = 0;
898 inode->i_data.a_ops = &def_blk_aops;
899 mapping_set_gfp_mask(&inode->i_data, GFP_USER);
900
901 bdev = I_BDEV(inode);
902 mutex_init(&bdev->bd_fsfreeze_mutex);
903 spin_lock_init(&bdev->bd_size_lock);
904 bdev->bd_disk = disk;
905 bdev->bd_partno = partno;
906 bdev->bd_inode = inode;
907 bdev->bd_stats = alloc_percpu(struct disk_stats);
908 if (!bdev->bd_stats) {
909 iput(inode);
910 return NULL;
911 }
912 return bdev;
913 }
914
915 void bdev_add(struct block_device *bdev, dev_t dev)
916 {
917 bdev->bd_dev = dev;
918 bdev->bd_inode->i_rdev = dev;
919 bdev->bd_inode->i_ino = dev;
920 insert_inode_hash(bdev->bd_inode);
921 }
922
923 long nr_blockdev_pages(void)
924 {
925 struct inode *inode;
926 long ret = 0;
927
928 spin_lock(&blockdev_superblock->s_inode_list_lock);
929 list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list)
930 ret += inode->i_mapping->nrpages;
931 spin_unlock(&blockdev_superblock->s_inode_list_lock);
932
933 return ret;
934 }
935
936 /**
937 * bd_may_claim - test whether a block device can be claimed
938 * @bdev: block device of interest
939 * @whole: whole block device containing @bdev, may equal @bdev
940 * @holder: holder trying to claim @bdev
941 *
942 * Test whether @bdev can be claimed by @holder.
943 *
944 * CONTEXT:
945 * spin_lock(&bdev_lock).
946 *
947 * RETURNS:
948 * %true if @bdev can be claimed, %false otherwise.
949 */
950 static bool bd_may_claim(struct block_device *bdev, struct block_device *whole,
951 void *holder)
952 {
953 if (bdev->bd_holder == holder)
954 return true; /* already a holder */
955 else if (bdev->bd_holder != NULL)
956 return false; /* held by someone else */
957 else if (whole == bdev)
958 return true; /* is a whole device which isn't held */
959
960 else if (whole->bd_holder == bd_may_claim)
961 return true; /* is a partition of a device that is being partitioned */
962 else if (whole->bd_holder != NULL)
963 return false; /* is a partition of a held device */
964 else
965 return true; /* is a partition of an un-held device */
966 }
967
968 /**
969 * bd_prepare_to_claim - claim a block device
970 * @bdev: block device of interest
971 * @holder: holder trying to claim @bdev
972 *
973 * Claim @bdev. This function fails if @bdev is already claimed by another
974 * holder and waits if another claiming is in progress. return, the caller
975 * has ownership of bd_claiming and bd_holder[s].
976 *
977 * RETURNS:
978 * 0 if @bdev can be claimed, -EBUSY otherwise.
979 */
980 int bd_prepare_to_claim(struct block_device *bdev, void *holder)
981 {
982 struct block_device *whole = bdev_whole(bdev);
983
984 if (WARN_ON_ONCE(!holder))
985 return -EINVAL;
986 retry:
987 spin_lock(&bdev_lock);
988 /* if someone else claimed, fail */
989 if (!bd_may_claim(bdev, whole, holder)) {
990 spin_unlock(&bdev_lock);
991 return -EBUSY;
992 }
993
994 /* if claiming is already in progress, wait for it to finish */
995 if (whole->bd_claiming) {
996 wait_queue_head_t *wq = bit_waitqueue(&whole->bd_claiming, 0);
997 DEFINE_WAIT(wait);
998
999 prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
1000 spin_unlock(&bdev_lock);
1001 schedule();
1002 finish_wait(wq, &wait);
1003 goto retry;
1004 }
1005
1006 /* yay, all mine */
1007 whole->bd_claiming = holder;
1008 spin_unlock(&bdev_lock);
1009 return 0;
1010 }
1011 EXPORT_SYMBOL_GPL(bd_prepare_to_claim); /* only for the loop driver */
1012
1013 static void bd_clear_claiming(struct block_device *whole, void *holder)
1014 {
1015 lockdep_assert_held(&bdev_lock);
1016 /* tell others that we're done */
1017 BUG_ON(whole->bd_claiming != holder);
1018 whole->bd_claiming = NULL;
1019 wake_up_bit(&whole->bd_claiming, 0);
1020 }
1021
1022 /**
1023 * bd_finish_claiming - finish claiming of a block device
1024 * @bdev: block device of interest
1025 * @holder: holder that has claimed @bdev
1026 *
1027 * Finish exclusive open of a block device. Mark the device as exlusively
1028 * open by the holder and wake up all waiters for exclusive open to finish.
1029 */
1030 static void bd_finish_claiming(struct block_device *bdev, void *holder)
1031 {
1032 struct block_device *whole = bdev_whole(bdev);
1033
1034 spin_lock(&bdev_lock);
1035 BUG_ON(!bd_may_claim(bdev, whole, holder));
1036 /*
1037 * Note that for a whole device bd_holders will be incremented twice,
1038 * and bd_holder will be set to bd_may_claim before being set to holder
1039 */
1040 whole->bd_holders++;
1041 whole->bd_holder = bd_may_claim;
1042 bdev->bd_holders++;
1043 bdev->bd_holder = holder;
1044 bd_clear_claiming(whole, holder);
1045 spin_unlock(&bdev_lock);
1046 }
1047
1048 /**
1049 * bd_abort_claiming - abort claiming of a block device
1050 * @bdev: block device of interest
1051 * @holder: holder that has claimed @bdev
1052 *
1053 * Abort claiming of a block device when the exclusive open failed. This can be
1054 * also used when exclusive open is not actually desired and we just needed
1055 * to block other exclusive openers for a while.
1056 */
1057 void bd_abort_claiming(struct block_device *bdev, void *holder)
1058 {
1059 spin_lock(&bdev_lock);
1060 bd_clear_claiming(bdev_whole(bdev), holder);
1061 spin_unlock(&bdev_lock);
1062 }
1063 EXPORT_SYMBOL(bd_abort_claiming);
1064
1065 static void blkdev_flush_mapping(struct block_device *bdev)
1066 {
1067 WARN_ON_ONCE(bdev->bd_holders);
1068 sync_blockdev(bdev);
1069 kill_bdev(bdev);
1070 bdev_write_inode(bdev);
1071 }
1072
1073 static int blkdev_get_whole(struct block_device *bdev, fmode_t mode)
1074 {
1075 struct gendisk *disk = bdev->bd_disk;
1076 int ret = 0;
1077
1078 if (disk->fops->open) {
1079 ret = disk->fops->open(bdev, mode);
1080 if (ret) {
1081 /* avoid ghost partitions on a removed medium */
1082 if (ret == -ENOMEDIUM &&
1083 test_bit(GD_NEED_PART_SCAN, &disk->state))
1084 bdev_disk_changed(disk, true);
1085 return ret;
1086 }
1087 }
1088
1089 if (!bdev->bd_openers)
1090 set_init_blocksize(bdev);
1091 if (test_bit(GD_NEED_PART_SCAN, &disk->state))
1092 bdev_disk_changed(disk, false);
1093 bdev->bd_openers++;
1094 return 0;;
1095 }
1096
1097 static void blkdev_put_whole(struct block_device *bdev, fmode_t mode)
1098 {
1099 if (!--bdev->bd_openers)
1100 blkdev_flush_mapping(bdev);
1101 if (bdev->bd_disk->fops->release)
1102 bdev->bd_disk->fops->release(bdev->bd_disk, mode);
1103 }
1104
1105 static int blkdev_get_part(struct block_device *part, fmode_t mode)
1106 {
1107 struct gendisk *disk = part->bd_disk;
1108 int ret;
1109
1110 if (part->bd_openers)
1111 goto done;
1112
1113 ret = blkdev_get_whole(bdev_whole(part), mode);
1114 if (ret)
1115 return ret;
1116
1117 ret = -ENXIO;
1118 if (!bdev_nr_sectors(part))
1119 goto out_blkdev_put;
1120
1121 disk->open_partitions++;
1122 set_init_blocksize(part);
1123 done:
1124 part->bd_openers++;
1125 return 0;
1126
1127 out_blkdev_put:
1128 blkdev_put_whole(bdev_whole(part), mode);
1129 return ret;
1130 }
1131
1132 static void blkdev_put_part(struct block_device *part, fmode_t mode)
1133 {
1134 struct block_device *whole = bdev_whole(part);
1135
1136 if (--part->bd_openers)
1137 return;
1138 blkdev_flush_mapping(part);
1139 whole->bd_disk->open_partitions--;
1140 blkdev_put_whole(whole, mode);
1141 }
1142
1143 struct block_device *blkdev_get_no_open(dev_t dev)
1144 {
1145 struct block_device *bdev;
1146 struct inode *inode;
1147
1148 inode = ilookup(blockdev_superblock, dev);
1149 if (!inode) {
1150 blk_request_module(dev);
1151 inode = ilookup(blockdev_superblock, dev);
1152 if (!inode)
1153 return NULL;
1154 }
1155
1156 /* switch from the inode reference to a device mode one: */
1157 bdev = &BDEV_I(inode)->bdev;
1158 if (!kobject_get_unless_zero(&bdev->bd_device.kobj))
1159 bdev = NULL;
1160 iput(inode);
1161
1162 if (!bdev)
1163 return NULL;
1164 if ((bdev->bd_disk->flags & GENHD_FL_HIDDEN) ||
1165 !try_module_get(bdev->bd_disk->fops->owner)) {
1166 put_device(&bdev->bd_device);
1167 return NULL;
1168 }
1169
1170 return bdev;
1171 }
1172
1173 void blkdev_put_no_open(struct block_device *bdev)
1174 {
1175 module_put(bdev->bd_disk->fops->owner);
1176 put_device(&bdev->bd_device);
1177 }
1178
1179 /**
1180 * blkdev_get_by_dev - open a block device by device number
1181 * @dev: device number of block device to open
1182 * @mode: FMODE_* mask
1183 * @holder: exclusive holder identifier
1184 *
1185 * Open the block device described by device number @dev. If @mode includes
1186 * %FMODE_EXCL, the block device is opened with exclusive access. Specifying
1187 * %FMODE_EXCL with a %NULL @holder is invalid. Exclusive opens may nest for
1188 * the same @holder.
1189 *
1190 * Use this interface ONLY if you really do not have anything better - i.e. when
1191 * you are behind a truly sucky interface and all you are given is a device
1192 * number. Everything else should use blkdev_get_by_path().
1193 *
1194 * CONTEXT:
1195 * Might sleep.
1196 *
1197 * RETURNS:
1198 * Reference to the block_device on success, ERR_PTR(-errno) on failure.
1199 */
1200 struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode, void *holder)
1201 {
1202 bool unblock_events = true;
1203 struct block_device *bdev;
1204 struct gendisk *disk;
1205 int ret;
1206
1207 ret = devcgroup_check_permission(DEVCG_DEV_BLOCK,
1208 MAJOR(dev), MINOR(dev),
1209 ((mode & FMODE_READ) ? DEVCG_ACC_READ : 0) |
1210 ((mode & FMODE_WRITE) ? DEVCG_ACC_WRITE : 0));
1211 if (ret)
1212 return ERR_PTR(ret);
1213
1214 bdev = blkdev_get_no_open(dev);
1215 if (!bdev)
1216 return ERR_PTR(-ENXIO);
1217 disk = bdev->bd_disk;
1218
1219 if (mode & FMODE_EXCL) {
1220 ret = bd_prepare_to_claim(bdev, holder);
1221 if (ret)
1222 goto put_blkdev;
1223 }
1224
1225 disk_block_events(disk);
1226
1227 mutex_lock(&disk->open_mutex);
1228 ret = -ENXIO;
1229 if (!disk_live(disk))
1230 goto abort_claiming;
1231 if (bdev_is_partition(bdev))
1232 ret = blkdev_get_part(bdev, mode);
1233 else
1234 ret = blkdev_get_whole(bdev, mode);
1235 if (ret)
1236 goto abort_claiming;
1237 if (mode & FMODE_EXCL) {
1238 bd_finish_claiming(bdev, holder);
1239
1240 /*
1241 * Block event polling for write claims if requested. Any write
1242 * holder makes the write_holder state stick until all are
1243 * released. This is good enough and tracking individual
1244 * writeable reference is too fragile given the way @mode is
1245 * used in blkdev_get/put().
1246 */
1247 if ((mode & FMODE_WRITE) && !bdev->bd_write_holder &&
1248 (disk->flags & GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE)) {
1249 bdev->bd_write_holder = true;
1250 unblock_events = false;
1251 }
1252 }
1253 mutex_unlock(&disk->open_mutex);
1254
1255 if (unblock_events)
1256 disk_unblock_events(disk);
1257 return bdev;
1258
1259 abort_claiming:
1260 if (mode & FMODE_EXCL)
1261 bd_abort_claiming(bdev, holder);
1262 mutex_unlock(&disk->open_mutex);
1263 disk_unblock_events(disk);
1264 put_blkdev:
1265 blkdev_put_no_open(bdev);
1266 return ERR_PTR(ret);
1267 }
1268 EXPORT_SYMBOL(blkdev_get_by_dev);
1269
1270 /**
1271 * blkdev_get_by_path - open a block device by name
1272 * @path: path to the block device to open
1273 * @mode: FMODE_* mask
1274 * @holder: exclusive holder identifier
1275 *
1276 * Open the block device described by the device file at @path. If @mode
1277 * includes %FMODE_EXCL, the block device is opened with exclusive access.
1278 * Specifying %FMODE_EXCL with a %NULL @holder is invalid. Exclusive opens may
1279 * nest for the same @holder.
1280 *
1281 * CONTEXT:
1282 * Might sleep.
1283 *
1284 * RETURNS:
1285 * Reference to the block_device on success, ERR_PTR(-errno) on failure.
1286 */
1287 struct block_device *blkdev_get_by_path(const char *path, fmode_t mode,
1288 void *holder)
1289 {
1290 struct block_device *bdev;
1291 dev_t dev;
1292 int error;
1293
1294 error = lookup_bdev(path, &dev);
1295 if (error)
1296 return ERR_PTR(error);
1297
1298 bdev = blkdev_get_by_dev(dev, mode, holder);
1299 if (!IS_ERR(bdev) && (mode & FMODE_WRITE) && bdev_read_only(bdev)) {
1300 blkdev_put(bdev, mode);
1301 return ERR_PTR(-EACCES);
1302 }
1303
1304 return bdev;
1305 }
1306 EXPORT_SYMBOL(blkdev_get_by_path);
1307
1308 static int blkdev_open(struct inode * inode, struct file * filp)
1309 {
1310 struct block_device *bdev;
1311
1312 /*
1313 * Preserve backwards compatibility and allow large file access
1314 * even if userspace doesn't ask for it explicitly. Some mkfs
1315 * binary needs it. We might want to drop this workaround
1316 * during an unstable branch.
1317 */
1318 filp->f_flags |= O_LARGEFILE;
1319
1320 filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC;
1321
1322 if (filp->f_flags & O_NDELAY)
1323 filp->f_mode |= FMODE_NDELAY;
1324 if (filp->f_flags & O_EXCL)
1325 filp->f_mode |= FMODE_EXCL;
1326 if ((filp->f_flags & O_ACCMODE) == 3)
1327 filp->f_mode |= FMODE_WRITE_IOCTL;
1328
1329 bdev = blkdev_get_by_dev(inode->i_rdev, filp->f_mode, filp);
1330 if (IS_ERR(bdev))
1331 return PTR_ERR(bdev);
1332 filp->f_mapping = bdev->bd_inode->i_mapping;
1333 filp->f_wb_err = filemap_sample_wb_err(filp->f_mapping);
1334 return 0;
1335 }
1336
1337 void blkdev_put(struct block_device *bdev, fmode_t mode)
1338 {
1339 struct gendisk *disk = bdev->bd_disk;
1340
1341 /*
1342 * Sync early if it looks like we're the last one. If someone else
1343 * opens the block device between now and the decrement of bd_openers
1344 * then we did a sync that we didn't need to, but that's not the end
1345 * of the world and we want to avoid long (could be several minute)
1346 * syncs while holding the mutex.
1347 */
1348 if (bdev->bd_openers == 1)
1349 sync_blockdev(bdev);
1350
1351 mutex_lock(&disk->open_mutex);
1352 if (mode & FMODE_EXCL) {
1353 struct block_device *whole = bdev_whole(bdev);
1354 bool bdev_free;
1355
1356 /*
1357 * Release a claim on the device. The holder fields
1358 * are protected with bdev_lock. open_mutex is to
1359 * synchronize disk_holder unlinking.
1360 */
1361 spin_lock(&bdev_lock);
1362
1363 WARN_ON_ONCE(--bdev->bd_holders < 0);
1364 WARN_ON_ONCE(--whole->bd_holders < 0);
1365
1366 if ((bdev_free = !bdev->bd_holders))
1367 bdev->bd_holder = NULL;
1368 if (!whole->bd_holders)
1369 whole->bd_holder = NULL;
1370
1371 spin_unlock(&bdev_lock);
1372
1373 /*
1374 * If this was the last claim, remove holder link and
1375 * unblock evpoll if it was a write holder.
1376 */
1377 if (bdev_free && bdev->bd_write_holder) {
1378 disk_unblock_events(disk);
1379 bdev->bd_write_holder = false;
1380 }
1381 }
1382
1383 /*
1384 * Trigger event checking and tell drivers to flush MEDIA_CHANGE
1385 * event. This is to ensure detection of media removal commanded
1386 * from userland - e.g. eject(1).
1387 */
1388 disk_flush_events(disk, DISK_EVENT_MEDIA_CHANGE);
1389
1390 if (bdev_is_partition(bdev))
1391 blkdev_put_part(bdev, mode);
1392 else
1393 blkdev_put_whole(bdev, mode);
1394 mutex_unlock(&disk->open_mutex);
1395
1396 blkdev_put_no_open(bdev);
1397 }
1398 EXPORT_SYMBOL(blkdev_put);
1399
1400 static int blkdev_close(struct inode * inode, struct file * filp)
1401 {
1402 struct block_device *bdev = I_BDEV(bdev_file_inode(filp));
1403 blkdev_put(bdev, filp->f_mode);
1404 return 0;
1405 }
1406
1407 static long block_ioctl(struct file *file, unsigned cmd, unsigned long arg)
1408 {
1409 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
1410 fmode_t mode = file->f_mode;
1411
1412 /*
1413 * O_NDELAY can be altered using fcntl(.., F_SETFL, ..), so we have
1414 * to updated it before every ioctl.
1415 */
1416 if (file->f_flags & O_NDELAY)
1417 mode |= FMODE_NDELAY;
1418 else
1419 mode &= ~FMODE_NDELAY;
1420
1421 return blkdev_ioctl(bdev, mode, cmd, arg);
1422 }
1423
1424 /*
1425 * Write data to the block device. Only intended for the block device itself
1426 * and the raw driver which basically is a fake block device.
1427 *
1428 * Does not take i_mutex for the write and thus is not for general purpose
1429 * use.
1430 */
1431 static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
1432 {
1433 struct file *file = iocb->ki_filp;
1434 struct inode *bd_inode = bdev_file_inode(file);
1435 loff_t size = i_size_read(bd_inode);
1436 struct blk_plug plug;
1437 size_t shorted = 0;
1438 ssize_t ret;
1439
1440 if (bdev_read_only(I_BDEV(bd_inode)))
1441 return -EPERM;
1442
1443 if (IS_SWAPFILE(bd_inode) && !is_hibernate_resume_dev(bd_inode->i_rdev))
1444 return -ETXTBSY;
1445
1446 if (!iov_iter_count(from))
1447 return 0;
1448
1449 if (iocb->ki_pos >= size)
1450 return -ENOSPC;
1451
1452 if ((iocb->ki_flags & (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT)
1453 return -EOPNOTSUPP;
1454
1455 size -= iocb->ki_pos;
1456 if (iov_iter_count(from) > size) {
1457 shorted = iov_iter_count(from) - size;
1458 iov_iter_truncate(from, size);
1459 }
1460
1461 blk_start_plug(&plug);
1462 ret = __generic_file_write_iter(iocb, from);
1463 if (ret > 0)
1464 ret = generic_write_sync(iocb, ret);
1465 iov_iter_reexpand(from, iov_iter_count(from) + shorted);
1466 blk_finish_plug(&plug);
1467 return ret;
1468 }
1469
1470 static ssize_t blkdev_read_iter(struct kiocb *iocb, struct iov_iter *to)
1471 {
1472 struct file *file = iocb->ki_filp;
1473 struct inode *bd_inode = bdev_file_inode(file);
1474 loff_t size = i_size_read(bd_inode);
1475 loff_t pos = iocb->ki_pos;
1476 size_t shorted = 0;
1477 ssize_t ret;
1478
1479 if (pos >= size)
1480 return 0;
1481
1482 size -= pos;
1483 if (iov_iter_count(to) > size) {
1484 shorted = iov_iter_count(to) - size;
1485 iov_iter_truncate(to, size);
1486 }
1487
1488 ret = generic_file_read_iter(iocb, to);
1489 iov_iter_reexpand(to, iov_iter_count(to) + shorted);
1490 return ret;
1491 }
1492
1493 static int blkdev_writepages(struct address_space *mapping,
1494 struct writeback_control *wbc)
1495 {
1496 return generic_writepages(mapping, wbc);
1497 }
1498
1499 static const struct address_space_operations def_blk_aops = {
1500 .set_page_dirty = __set_page_dirty_buffers,
1501 .readpage = blkdev_readpage,
1502 .readahead = blkdev_readahead,
1503 .writepage = blkdev_writepage,
1504 .write_begin = blkdev_write_begin,
1505 .write_end = blkdev_write_end,
1506 .writepages = blkdev_writepages,
1507 .direct_IO = blkdev_direct_IO,
1508 .migratepage = buffer_migrate_page_norefs,
1509 .is_dirty_writeback = buffer_check_dirty_writeback,
1510 };
1511
1512 #define BLKDEV_FALLOC_FL_SUPPORTED \
1513 (FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE | \
1514 FALLOC_FL_ZERO_RANGE | FALLOC_FL_NO_HIDE_STALE)
1515
1516 static long blkdev_fallocate(struct file *file, int mode, loff_t start,
1517 loff_t len)
1518 {
1519 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
1520 loff_t end = start + len - 1;
1521 loff_t isize;
1522 int error;
1523
1524 /* Fail if we don't recognize the flags. */
1525 if (mode & ~BLKDEV_FALLOC_FL_SUPPORTED)
1526 return -EOPNOTSUPP;
1527
1528 /* Don't go off the end of the device. */
1529 isize = i_size_read(bdev->bd_inode);
1530 if (start >= isize)
1531 return -EINVAL;
1532 if (end >= isize) {
1533 if (mode & FALLOC_FL_KEEP_SIZE) {
1534 len = isize - start;
1535 end = start + len - 1;
1536 } else
1537 return -EINVAL;
1538 }
1539
1540 /*
1541 * Don't allow IO that isn't aligned to logical block size.
1542 */
1543 if ((start | len) & (bdev_logical_block_size(bdev) - 1))
1544 return -EINVAL;
1545
1546 /* Invalidate the page cache, including dirty pages. */
1547 error = truncate_bdev_range(bdev, file->f_mode, start, end);
1548 if (error)
1549 return error;
1550
1551 switch (mode) {
1552 case FALLOC_FL_ZERO_RANGE:
1553 case FALLOC_FL_ZERO_RANGE | FALLOC_FL_KEEP_SIZE:
1554 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
1555 GFP_KERNEL, BLKDEV_ZERO_NOUNMAP);
1556 break;
1557 case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE:
1558 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
1559 GFP_KERNEL, BLKDEV_ZERO_NOFALLBACK);
1560 break;
1561 case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE | FALLOC_FL_NO_HIDE_STALE:
1562 error = blkdev_issue_discard(bdev, start >> 9, len >> 9,
1563 GFP_KERNEL, 0);
1564 break;
1565 default:
1566 return -EOPNOTSUPP;
1567 }
1568 if (error)
1569 return error;
1570
1571 /*
1572 * Invalidate the page cache again; if someone wandered in and dirtied
1573 * a page, we just discard it - userspace has no way of knowing whether
1574 * the write happened before or after discard completing...
1575 */
1576 return truncate_bdev_range(bdev, file->f_mode, start, end);
1577 }
1578
1579 const struct file_operations def_blk_fops = {
1580 .open = blkdev_open,
1581 .release = blkdev_close,
1582 .llseek = block_llseek,
1583 .read_iter = blkdev_read_iter,
1584 .write_iter = blkdev_write_iter,
1585 .iopoll = blkdev_iopoll,
1586 .mmap = generic_file_mmap,
1587 .fsync = blkdev_fsync,
1588 .unlocked_ioctl = block_ioctl,
1589 #ifdef CONFIG_COMPAT
1590 .compat_ioctl = compat_blkdev_ioctl,
1591 #endif
1592 .splice_read = generic_file_splice_read,
1593 .splice_write = iter_file_splice_write,
1594 .fallocate = blkdev_fallocate,
1595 };
1596
1597 /**
1598 * lookup_bdev - lookup a struct block_device by name
1599 * @pathname: special file representing the block device
1600 * @dev: return value of the block device's dev_t
1601 *
1602 * Get a reference to the blockdevice at @pathname in the current
1603 * namespace if possible and return it. Return ERR_PTR(error)
1604 * otherwise.
1605 */
1606 int lookup_bdev(const char *pathname, dev_t *dev)
1607 {
1608 struct inode *inode;
1609 struct path path;
1610 int error;
1611
1612 if (!pathname || !*pathname)
1613 return -EINVAL;
1614
1615 error = kern_path(pathname, LOOKUP_FOLLOW, &path);
1616 if (error)
1617 return error;
1618
1619 inode = d_backing_inode(path.dentry);
1620 error = -ENOTBLK;
1621 if (!S_ISBLK(inode->i_mode))
1622 goto out_path_put;
1623 error = -EACCES;
1624 if (!may_open_dev(&path))
1625 goto out_path_put;
1626
1627 *dev = inode->i_rdev;
1628 error = 0;
1629 out_path_put:
1630 path_put(&path);
1631 return error;
1632 }
1633 EXPORT_SYMBOL(lookup_bdev);
1634
1635 int __invalidate_device(struct block_device *bdev, bool kill_dirty)
1636 {
1637 struct super_block *sb = get_super(bdev);
1638 int res = 0;
1639
1640 if (sb) {
1641 /*
1642 * no need to lock the super, get_super holds the
1643 * read mutex so the filesystem cannot go away
1644 * under us (->put_super runs with the write lock
1645 * hold).
1646 */
1647 shrink_dcache_sb(sb);
1648 res = invalidate_inodes(sb, kill_dirty);
1649 drop_super(sb);
1650 }
1651 invalidate_bdev(bdev);
1652 return res;
1653 }
1654 EXPORT_SYMBOL(__invalidate_device);
1655
1656 void iterate_bdevs(void (*func)(struct block_device *, void *), void *arg)
1657 {
1658 struct inode *inode, *old_inode = NULL;
1659
1660 spin_lock(&blockdev_superblock->s_inode_list_lock);
1661 list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list) {
1662 struct address_space *mapping = inode->i_mapping;
1663 struct block_device *bdev;
1664
1665 spin_lock(&inode->i_lock);
1666 if (inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW) ||
1667 mapping->nrpages == 0) {
1668 spin_unlock(&inode->i_lock);
1669 continue;
1670 }
1671 __iget(inode);
1672 spin_unlock(&inode->i_lock);
1673 spin_unlock(&blockdev_superblock->s_inode_list_lock);
1674 /*
1675 * We hold a reference to 'inode' so it couldn't have been
1676 * removed from s_inodes list while we dropped the
1677 * s_inode_list_lock We cannot iput the inode now as we can
1678 * be holding the last reference and we cannot iput it under
1679 * s_inode_list_lock. So we keep the reference and iput it
1680 * later.
1681 */
1682 iput(old_inode);
1683 old_inode = inode;
1684 bdev = I_BDEV(inode);
1685
1686 mutex_lock(&bdev->bd_disk->open_mutex);
1687 if (bdev->bd_openers)
1688 func(bdev, arg);
1689 mutex_unlock(&bdev->bd_disk->open_mutex);
1690
1691 spin_lock(&blockdev_superblock->s_inode_list_lock);
1692 }
1693 spin_unlock(&blockdev_superblock->s_inode_list_lock);
1694 iput(old_inode);
1695 }