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