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/slab.h>
11 #include <linux/kmod.h>
12 #include <linux/major.h>
13 #include <linux/device_cgroup.h>
14 #include <linux/blkdev.h>
15 #include <linux/blk-integrity.h>
16 #include <linux/backing-dev.h>
17 #include <linux/module.h>
18 #include <linux/blkpg.h>
19 #include <linux/magic.h>
20 #include <linux/buffer_head.h>
21 #include <linux/swap.h>
22 #include <linux/writeback.h>
23 #include <linux/mount.h>
24 #include <linux/pseudo_fs.h>
25 #include <linux/uio.h>
26 #include <linux/namei.h>
27 #include <linux/cleancache.h>
28 #include <linux/part_stat.h>
29 #include <linux/uaccess.h>
30 #include <linux/stat.h>
31 #include "../fs/internal.h"
32 #include "blk.h"
33
34 struct bdev_inode {
35 struct block_device bdev;
36 struct inode vfs_inode;
37 };
38
BDEV_I(struct inode * inode)39 static inline struct bdev_inode *BDEV_I(struct inode *inode)
40 {
41 return container_of(inode, struct bdev_inode, vfs_inode);
42 }
43
I_BDEV(struct inode * inode)44 struct block_device *I_BDEV(struct inode *inode)
45 {
46 return &BDEV_I(inode)->bdev;
47 }
48 EXPORT_SYMBOL(I_BDEV);
49
bdev_write_inode(struct block_device * bdev)50 static void bdev_write_inode(struct block_device *bdev)
51 {
52 struct inode *inode = bdev->bd_inode;
53 int ret;
54
55 spin_lock(&inode->i_lock);
56 while (inode->i_state & I_DIRTY) {
57 spin_unlock(&inode->i_lock);
58 ret = write_inode_now(inode, true);
59 if (ret)
60 pr_warn_ratelimited(
61 "VFS: Dirty inode writeback failed for block device %pg (err=%d).\n",
62 bdev, ret);
63 spin_lock(&inode->i_lock);
64 }
65 spin_unlock(&inode->i_lock);
66 }
67
68 /* Kill _all_ buffers and pagecache , dirty or not.. */
kill_bdev(struct block_device * bdev)69 static void kill_bdev(struct block_device *bdev)
70 {
71 struct address_space *mapping = bdev->bd_inode->i_mapping;
72
73 if (mapping_empty(mapping))
74 return;
75
76 invalidate_bh_lrus();
77 truncate_inode_pages(mapping, 0);
78 }
79
80 /* Invalidate clean unused buffers and pagecache. */
invalidate_bdev(struct block_device * bdev)81 void invalidate_bdev(struct block_device *bdev)
82 {
83 struct address_space *mapping = bdev->bd_inode->i_mapping;
84
85 if (mapping->nrpages) {
86 invalidate_bh_lrus();
87 lru_add_drain_all(); /* make sure all lru add caches are flushed */
88 invalidate_mapping_pages(mapping, 0, -1);
89 }
90 /* 99% of the time, we don't need to flush the cleancache on the bdev.
91 * But, for the strange corners, lets be cautious
92 */
93 cleancache_invalidate_inode(mapping);
94 }
95 EXPORT_SYMBOL(invalidate_bdev);
96
97 /*
98 * Drop all buffers & page cache for given bdev range. This function bails
99 * with error if bdev has other exclusive owner (such as filesystem).
100 */
truncate_bdev_range(struct block_device * bdev,fmode_t mode,loff_t lstart,loff_t lend)101 int truncate_bdev_range(struct block_device *bdev, fmode_t mode,
102 loff_t lstart, loff_t lend)
103 {
104 /*
105 * If we don't hold exclusive handle for the device, upgrade to it
106 * while we discard the buffer cache to avoid discarding buffers
107 * under live filesystem.
108 */
109 if (!(mode & FMODE_EXCL)) {
110 int err = bd_prepare_to_claim(bdev, truncate_bdev_range);
111 if (err)
112 goto invalidate;
113 }
114
115 truncate_inode_pages_range(bdev->bd_inode->i_mapping, lstart, lend);
116 if (!(mode & FMODE_EXCL))
117 bd_abort_claiming(bdev, truncate_bdev_range);
118 return 0;
119
120 invalidate:
121 /*
122 * Someone else has handle exclusively open. Try invalidating instead.
123 * The 'end' argument is inclusive so the rounding is safe.
124 */
125 return invalidate_inode_pages2_range(bdev->bd_inode->i_mapping,
126 lstart >> PAGE_SHIFT,
127 lend >> PAGE_SHIFT);
128 }
129
set_init_blocksize(struct block_device * bdev)130 static void set_init_blocksize(struct block_device *bdev)
131 {
132 unsigned int bsize = bdev_logical_block_size(bdev);
133 loff_t size = i_size_read(bdev->bd_inode);
134
135 while (bsize < PAGE_SIZE) {
136 if (size & bsize)
137 break;
138 bsize <<= 1;
139 }
140 bdev->bd_inode->i_blkbits = blksize_bits(bsize);
141 }
142
set_blocksize(struct block_device * bdev,int size)143 int set_blocksize(struct block_device *bdev, int size)
144 {
145 /* Size must be a power of two, and between 512 and PAGE_SIZE */
146 if (size > PAGE_SIZE || size < 512 || !is_power_of_2(size))
147 return -EINVAL;
148
149 /* Size cannot be smaller than the size supported by the device */
150 if (size < bdev_logical_block_size(bdev))
151 return -EINVAL;
152
153 /* Don't change the size if it is same as current */
154 if (bdev->bd_inode->i_blkbits != blksize_bits(size)) {
155 sync_blockdev(bdev);
156 bdev->bd_inode->i_blkbits = blksize_bits(size);
157 kill_bdev(bdev);
158 }
159 return 0;
160 }
161
162 EXPORT_SYMBOL(set_blocksize);
163
sb_set_blocksize(struct super_block * sb,int size)164 int sb_set_blocksize(struct super_block *sb, int size)
165 {
166 if (set_blocksize(sb->s_bdev, size))
167 return 0;
168 /* If we get here, we know size is power of two
169 * and it's value is between 512 and PAGE_SIZE */
170 sb->s_blocksize = size;
171 sb->s_blocksize_bits = blksize_bits(size);
172 return sb->s_blocksize;
173 }
174
175 EXPORT_SYMBOL(sb_set_blocksize);
176
sb_min_blocksize(struct super_block * sb,int size)177 int sb_min_blocksize(struct super_block *sb, int size)
178 {
179 int minsize = bdev_logical_block_size(sb->s_bdev);
180 if (size < minsize)
181 size = minsize;
182 return sb_set_blocksize(sb, size);
183 }
184
185 EXPORT_SYMBOL(sb_min_blocksize);
186
sync_blockdev_nowait(struct block_device * bdev)187 int sync_blockdev_nowait(struct block_device *bdev)
188 {
189 if (!bdev)
190 return 0;
191 return filemap_flush(bdev->bd_inode->i_mapping);
192 }
193 EXPORT_SYMBOL_GPL(sync_blockdev_nowait);
194
195 /*
196 * Write out and wait upon all the dirty data associated with a block
197 * device via its mapping. Does not take the superblock lock.
198 */
sync_blockdev(struct block_device * bdev)199 int sync_blockdev(struct block_device *bdev)
200 {
201 if (!bdev)
202 return 0;
203 return filemap_write_and_wait(bdev->bd_inode->i_mapping);
204 }
205 EXPORT_SYMBOL(sync_blockdev);
206
sync_blockdev_range(struct block_device * bdev,loff_t lstart,loff_t lend)207 int sync_blockdev_range(struct block_device *bdev, loff_t lstart, loff_t lend)
208 {
209 return filemap_write_and_wait_range(bdev->bd_inode->i_mapping,
210 lstart, lend);
211 }
212 EXPORT_SYMBOL(sync_blockdev_range);
213
214 /*
215 * Write out and wait upon all dirty data associated with this
216 * device. Filesystem data as well as the underlying block
217 * device. Takes the superblock lock.
218 */
fsync_bdev(struct block_device * bdev)219 int fsync_bdev(struct block_device *bdev)
220 {
221 struct super_block *sb = get_super(bdev);
222 if (sb) {
223 int res = sync_filesystem(sb);
224 drop_super(sb);
225 return res;
226 }
227 return sync_blockdev(bdev);
228 }
229 EXPORT_SYMBOL(fsync_bdev);
230
231 /**
232 * freeze_bdev -- lock a filesystem and force it into a consistent state
233 * @bdev: blockdevice to lock
234 *
235 * If a superblock is found on this device, we take the s_umount semaphore
236 * on it to make sure nobody unmounts until the snapshot creation is done.
237 * The reference counter (bd_fsfreeze_count) guarantees that only the last
238 * unfreeze process can unfreeze the frozen filesystem actually when multiple
239 * freeze requests arrive simultaneously. It counts up in freeze_bdev() and
240 * count down in thaw_bdev(). When it becomes 0, thaw_bdev() will unfreeze
241 * actually.
242 */
freeze_bdev(struct block_device * bdev)243 int freeze_bdev(struct block_device *bdev)
244 {
245 struct super_block *sb;
246 int error = 0;
247
248 mutex_lock(&bdev->bd_fsfreeze_mutex);
249 if (++bdev->bd_fsfreeze_count > 1)
250 goto done;
251
252 sb = get_active_super(bdev);
253 if (!sb)
254 goto sync;
255 if (sb->s_op->freeze_super)
256 error = sb->s_op->freeze_super(sb);
257 else
258 error = freeze_super(sb);
259 deactivate_super(sb);
260
261 if (error) {
262 bdev->bd_fsfreeze_count--;
263 goto done;
264 }
265 bdev->bd_fsfreeze_sb = sb;
266
267 sync:
268 sync_blockdev(bdev);
269 done:
270 mutex_unlock(&bdev->bd_fsfreeze_mutex);
271 return error;
272 }
273 EXPORT_SYMBOL(freeze_bdev);
274
275 /**
276 * thaw_bdev -- unlock filesystem
277 * @bdev: blockdevice to unlock
278 *
279 * Unlocks the filesystem and marks it writeable again after freeze_bdev().
280 */
thaw_bdev(struct block_device * bdev)281 int thaw_bdev(struct block_device *bdev)
282 {
283 struct super_block *sb;
284 int error = -EINVAL;
285
286 mutex_lock(&bdev->bd_fsfreeze_mutex);
287 if (!bdev->bd_fsfreeze_count)
288 goto out;
289
290 error = 0;
291 if (--bdev->bd_fsfreeze_count > 0)
292 goto out;
293
294 sb = bdev->bd_fsfreeze_sb;
295 if (!sb)
296 goto out;
297
298 if (sb->s_op->thaw_super)
299 error = sb->s_op->thaw_super(sb);
300 else
301 error = thaw_super(sb);
302 if (error)
303 bdev->bd_fsfreeze_count++;
304 else
305 bdev->bd_fsfreeze_sb = NULL;
306 out:
307 mutex_unlock(&bdev->bd_fsfreeze_mutex);
308 return error;
309 }
310 EXPORT_SYMBOL(thaw_bdev);
311
312 /**
313 * bdev_read_page() - Start reading a page from a block device
314 * @bdev: The device to read the page from
315 * @sector: The offset on the device to read the page to (need not be aligned)
316 * @page: The page to read
317 *
318 * On entry, the page should be locked. It will be unlocked when the page
319 * has been read. If the block driver implements rw_page synchronously,
320 * that will be true on exit from this function, but it need not be.
321 *
322 * Errors returned by this function are usually "soft", eg out of memory, or
323 * queue full; callers should try a different route to read this page rather
324 * than propagate an error back up the stack.
325 *
326 * Return: negative errno if an error occurs, 0 if submission was successful.
327 */
bdev_read_page(struct block_device * bdev,sector_t sector,struct page * page)328 int bdev_read_page(struct block_device *bdev, sector_t sector,
329 struct page *page)
330 {
331 const struct block_device_operations *ops = bdev->bd_disk->fops;
332 int result = -EOPNOTSUPP;
333
334 if (!ops->rw_page || bdev_get_integrity(bdev))
335 return result;
336
337 result = blk_queue_enter(bdev_get_queue(bdev), 0);
338 if (result)
339 return result;
340 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
341 REQ_OP_READ);
342 blk_queue_exit(bdev_get_queue(bdev));
343 return result;
344 }
345
346 /**
347 * bdev_write_page() - Start writing a page to a block device
348 * @bdev: The device to write the page to
349 * @sector: The offset on the device to write the page to (need not be aligned)
350 * @page: The page to write
351 * @wbc: The writeback_control for the write
352 *
353 * On entry, the page should be locked and not currently under writeback.
354 * On exit, if the write started successfully, the page will be unlocked and
355 * under writeback. If the write failed already (eg the driver failed to
356 * queue the page to the device), the page will still be locked. If the
357 * caller is a ->writepage implementation, it will need to unlock the page.
358 *
359 * Errors returned by this function are usually "soft", eg out of memory, or
360 * queue full; callers should try a different route to write this page rather
361 * than propagate an error back up the stack.
362 *
363 * Return: negative errno if an error occurs, 0 if submission was successful.
364 */
bdev_write_page(struct block_device * bdev,sector_t sector,struct page * page,struct writeback_control * wbc)365 int bdev_write_page(struct block_device *bdev, sector_t sector,
366 struct page *page, struct writeback_control *wbc)
367 {
368 int result;
369 const struct block_device_operations *ops = bdev->bd_disk->fops;
370
371 if (!ops->rw_page || bdev_get_integrity(bdev))
372 return -EOPNOTSUPP;
373 result = blk_queue_enter(bdev_get_queue(bdev), 0);
374 if (result)
375 return result;
376
377 set_page_writeback(page);
378 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
379 REQ_OP_WRITE);
380 if (result) {
381 end_page_writeback(page);
382 } else {
383 clean_page_buffers(page);
384 unlock_page(page);
385 }
386 blk_queue_exit(bdev_get_queue(bdev));
387 return result;
388 }
389
390 /*
391 * pseudo-fs
392 */
393
394 static __cacheline_aligned_in_smp DEFINE_SPINLOCK(bdev_lock);
395 static struct kmem_cache * bdev_cachep __read_mostly;
396
bdev_alloc_inode(struct super_block * sb)397 static struct inode *bdev_alloc_inode(struct super_block *sb)
398 {
399 struct bdev_inode *ei = alloc_inode_sb(sb, bdev_cachep, GFP_KERNEL);
400
401 if (!ei)
402 return NULL;
403 memset(&ei->bdev, 0, sizeof(ei->bdev));
404 return &ei->vfs_inode;
405 }
406
bdev_free_inode(struct inode * inode)407 static void bdev_free_inode(struct inode *inode)
408 {
409 struct block_device *bdev = I_BDEV(inode);
410
411 free_percpu(bdev->bd_stats);
412 kfree(bdev->bd_meta_info);
413
414 if (!bdev_is_partition(bdev)) {
415 if (bdev->bd_disk && bdev->bd_disk->bdi)
416 bdi_put(bdev->bd_disk->bdi);
417 kfree(bdev->bd_disk);
418 }
419
420 if (MAJOR(bdev->bd_dev) == BLOCK_EXT_MAJOR)
421 blk_free_ext_minor(MINOR(bdev->bd_dev));
422
423 kmem_cache_free(bdev_cachep, BDEV_I(inode));
424 }
425
init_once(void * data)426 static void init_once(void *data)
427 {
428 struct bdev_inode *ei = data;
429
430 inode_init_once(&ei->vfs_inode);
431 }
432
bdev_evict_inode(struct inode * inode)433 static void bdev_evict_inode(struct inode *inode)
434 {
435 truncate_inode_pages_final(&inode->i_data);
436 invalidate_inode_buffers(inode); /* is it needed here? */
437 clear_inode(inode);
438 }
439
440 static const struct super_operations bdev_sops = {
441 .statfs = simple_statfs,
442 .alloc_inode = bdev_alloc_inode,
443 .free_inode = bdev_free_inode,
444 .drop_inode = generic_delete_inode,
445 .evict_inode = bdev_evict_inode,
446 };
447
bd_init_fs_context(struct fs_context * fc)448 static int bd_init_fs_context(struct fs_context *fc)
449 {
450 struct pseudo_fs_context *ctx = init_pseudo(fc, BDEVFS_MAGIC);
451 if (!ctx)
452 return -ENOMEM;
453 fc->s_iflags |= SB_I_CGROUPWB;
454 ctx->ops = &bdev_sops;
455 return 0;
456 }
457
458 static struct file_system_type bd_type = {
459 .name = "bdev",
460 .init_fs_context = bd_init_fs_context,
461 .kill_sb = kill_anon_super,
462 };
463
464 struct super_block *blockdev_superblock __read_mostly;
465 EXPORT_SYMBOL_GPL(blockdev_superblock);
466
bdev_cache_init(void)467 void __init bdev_cache_init(void)
468 {
469 int err;
470 static struct vfsmount *bd_mnt;
471
472 bdev_cachep = kmem_cache_create("bdev_cache", sizeof(struct bdev_inode),
473 0, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
474 SLAB_MEM_SPREAD|SLAB_ACCOUNT|SLAB_PANIC),
475 init_once);
476 err = register_filesystem(&bd_type);
477 if (err)
478 panic("Cannot register bdev pseudo-fs");
479 bd_mnt = kern_mount(&bd_type);
480 if (IS_ERR(bd_mnt))
481 panic("Cannot create bdev pseudo-fs");
482 blockdev_superblock = bd_mnt->mnt_sb; /* For writeback */
483 }
484
bdev_alloc(struct gendisk * disk,u8 partno)485 struct block_device *bdev_alloc(struct gendisk *disk, u8 partno)
486 {
487 struct block_device *bdev;
488 struct inode *inode;
489
490 inode = new_inode(blockdev_superblock);
491 if (!inode)
492 return NULL;
493 inode->i_mode = S_IFBLK;
494 inode->i_rdev = 0;
495 inode->i_data.a_ops = &def_blk_aops;
496 mapping_set_gfp_mask(&inode->i_data, GFP_USER);
497
498 bdev = I_BDEV(inode);
499 mutex_init(&bdev->bd_fsfreeze_mutex);
500 spin_lock_init(&bdev->bd_size_lock);
501 bdev->bd_partno = partno;
502 bdev->bd_inode = inode;
503 bdev->bd_queue = disk->queue;
504 bdev->bd_stats = alloc_percpu(struct disk_stats);
505 if (!bdev->bd_stats) {
506 iput(inode);
507 return NULL;
508 }
509 bdev->bd_disk = disk;
510 return bdev;
511 }
512
bdev_add(struct block_device * bdev,dev_t dev)513 void bdev_add(struct block_device *bdev, dev_t dev)
514 {
515 if (bdev_stable_writes(bdev))
516 mapping_set_stable_writes(bdev->bd_inode->i_mapping);
517 bdev->bd_dev = dev;
518 bdev->bd_inode->i_rdev = dev;
519 bdev->bd_inode->i_ino = dev;
520 insert_inode_hash(bdev->bd_inode);
521 }
522
nr_blockdev_pages(void)523 long nr_blockdev_pages(void)
524 {
525 struct inode *inode;
526 long ret = 0;
527
528 spin_lock(&blockdev_superblock->s_inode_list_lock);
529 list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list)
530 ret += inode->i_mapping->nrpages;
531 spin_unlock(&blockdev_superblock->s_inode_list_lock);
532
533 return ret;
534 }
535
536 /**
537 * bd_may_claim - test whether a block device can be claimed
538 * @bdev: block device of interest
539 * @whole: whole block device containing @bdev, may equal @bdev
540 * @holder: holder trying to claim @bdev
541 *
542 * Test whether @bdev can be claimed by @holder.
543 *
544 * CONTEXT:
545 * spin_lock(&bdev_lock).
546 *
547 * RETURNS:
548 * %true if @bdev can be claimed, %false otherwise.
549 */
bd_may_claim(struct block_device * bdev,struct block_device * whole,void * holder)550 static bool bd_may_claim(struct block_device *bdev, struct block_device *whole,
551 void *holder)
552 {
553 if (bdev->bd_holder == holder)
554 return true; /* already a holder */
555 else if (bdev->bd_holder != NULL)
556 return false; /* held by someone else */
557 else if (whole == bdev)
558 return true; /* is a whole device which isn't held */
559
560 else if (whole->bd_holder == bd_may_claim)
561 return true; /* is a partition of a device that is being partitioned */
562 else if (whole->bd_holder != NULL)
563 return false; /* is a partition of a held device */
564 else
565 return true; /* is a partition of an un-held device */
566 }
567
568 /**
569 * bd_prepare_to_claim - claim a block device
570 * @bdev: block device of interest
571 * @holder: holder trying to claim @bdev
572 *
573 * Claim @bdev. This function fails if @bdev is already claimed by another
574 * holder and waits if another claiming is in progress. return, the caller
575 * has ownership of bd_claiming and bd_holder[s].
576 *
577 * RETURNS:
578 * 0 if @bdev can be claimed, -EBUSY otherwise.
579 */
bd_prepare_to_claim(struct block_device * bdev,void * holder)580 int bd_prepare_to_claim(struct block_device *bdev, void *holder)
581 {
582 struct block_device *whole = bdev_whole(bdev);
583
584 if (WARN_ON_ONCE(!holder))
585 return -EINVAL;
586 retry:
587 spin_lock(&bdev_lock);
588 /* if someone else claimed, fail */
589 if (!bd_may_claim(bdev, whole, holder)) {
590 spin_unlock(&bdev_lock);
591 return -EBUSY;
592 }
593
594 /* if claiming is already in progress, wait for it to finish */
595 if (whole->bd_claiming) {
596 wait_queue_head_t *wq = bit_waitqueue(&whole->bd_claiming, 0);
597 DEFINE_WAIT(wait);
598
599 prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
600 spin_unlock(&bdev_lock);
601 schedule();
602 finish_wait(wq, &wait);
603 goto retry;
604 }
605
606 /* yay, all mine */
607 whole->bd_claiming = holder;
608 spin_unlock(&bdev_lock);
609 return 0;
610 }
611 EXPORT_SYMBOL_GPL(bd_prepare_to_claim); /* only for the loop driver */
612
bd_clear_claiming(struct block_device * whole,void * holder)613 static void bd_clear_claiming(struct block_device *whole, void *holder)
614 {
615 lockdep_assert_held(&bdev_lock);
616 /* tell others that we're done */
617 BUG_ON(whole->bd_claiming != holder);
618 whole->bd_claiming = NULL;
619 wake_up_bit(&whole->bd_claiming, 0);
620 }
621
622 /**
623 * bd_finish_claiming - finish claiming of a block device
624 * @bdev: block device of interest
625 * @holder: holder that has claimed @bdev
626 *
627 * Finish exclusive open of a block device. Mark the device as exlusively
628 * open by the holder and wake up all waiters for exclusive open to finish.
629 */
bd_finish_claiming(struct block_device * bdev,void * holder)630 static void bd_finish_claiming(struct block_device *bdev, void *holder)
631 {
632 struct block_device *whole = bdev_whole(bdev);
633
634 spin_lock(&bdev_lock);
635 BUG_ON(!bd_may_claim(bdev, whole, holder));
636 /*
637 * Note that for a whole device bd_holders will be incremented twice,
638 * and bd_holder will be set to bd_may_claim before being set to holder
639 */
640 whole->bd_holders++;
641 whole->bd_holder = bd_may_claim;
642 bdev->bd_holders++;
643 bdev->bd_holder = holder;
644 bd_clear_claiming(whole, holder);
645 spin_unlock(&bdev_lock);
646 }
647
648 /**
649 * bd_abort_claiming - abort claiming of a block device
650 * @bdev: block device of interest
651 * @holder: holder that has claimed @bdev
652 *
653 * Abort claiming of a block device when the exclusive open failed. This can be
654 * also used when exclusive open is not actually desired and we just needed
655 * to block other exclusive openers for a while.
656 */
bd_abort_claiming(struct block_device * bdev,void * holder)657 void bd_abort_claiming(struct block_device *bdev, void *holder)
658 {
659 spin_lock(&bdev_lock);
660 bd_clear_claiming(bdev_whole(bdev), holder);
661 spin_unlock(&bdev_lock);
662 }
663 EXPORT_SYMBOL(bd_abort_claiming);
664
blkdev_flush_mapping(struct block_device * bdev)665 static void blkdev_flush_mapping(struct block_device *bdev)
666 {
667 WARN_ON_ONCE(bdev->bd_holders);
668 sync_blockdev(bdev);
669 kill_bdev(bdev);
670 bdev_write_inode(bdev);
671 }
672
blkdev_get_whole(struct block_device * bdev,fmode_t mode)673 static int blkdev_get_whole(struct block_device *bdev, fmode_t mode)
674 {
675 struct gendisk *disk = bdev->bd_disk;
676 int ret;
677
678 if (disk->fops->open) {
679 ret = disk->fops->open(bdev, mode);
680 if (ret) {
681 /* avoid ghost partitions on a removed medium */
682 if (ret == -ENOMEDIUM &&
683 test_bit(GD_NEED_PART_SCAN, &disk->state))
684 bdev_disk_changed(disk, true);
685 return ret;
686 }
687 }
688
689 if (!atomic_read(&bdev->bd_openers))
690 set_init_blocksize(bdev);
691 if (test_bit(GD_NEED_PART_SCAN, &disk->state))
692 bdev_disk_changed(disk, false);
693 atomic_inc(&bdev->bd_openers);
694 return 0;
695 }
696
blkdev_put_whole(struct block_device * bdev,fmode_t mode)697 static void blkdev_put_whole(struct block_device *bdev, fmode_t mode)
698 {
699 if (atomic_dec_and_test(&bdev->bd_openers))
700 blkdev_flush_mapping(bdev);
701 if (bdev->bd_disk->fops->release)
702 bdev->bd_disk->fops->release(bdev->bd_disk, mode);
703 }
704
blkdev_get_part(struct block_device * part,fmode_t mode)705 static int blkdev_get_part(struct block_device *part, fmode_t mode)
706 {
707 struct gendisk *disk = part->bd_disk;
708 int ret;
709
710 if (atomic_read(&part->bd_openers))
711 goto done;
712
713 ret = blkdev_get_whole(bdev_whole(part), mode);
714 if (ret)
715 return ret;
716
717 ret = -ENXIO;
718 if (!bdev_nr_sectors(part))
719 goto out_blkdev_put;
720
721 disk->open_partitions++;
722 set_init_blocksize(part);
723 done:
724 atomic_inc(&part->bd_openers);
725 return 0;
726
727 out_blkdev_put:
728 blkdev_put_whole(bdev_whole(part), mode);
729 return ret;
730 }
731
blkdev_put_part(struct block_device * part,fmode_t mode)732 static void blkdev_put_part(struct block_device *part, fmode_t mode)
733 {
734 struct block_device *whole = bdev_whole(part);
735
736 if (!atomic_dec_and_test(&part->bd_openers))
737 return;
738 blkdev_flush_mapping(part);
739 whole->bd_disk->open_partitions--;
740 blkdev_put_whole(whole, mode);
741 }
742
blkdev_get_no_open(dev_t dev)743 struct block_device *blkdev_get_no_open(dev_t dev)
744 {
745 struct block_device *bdev;
746 struct inode *inode;
747
748 inode = ilookup(blockdev_superblock, dev);
749 if (!inode && IS_ENABLED(CONFIG_BLOCK_LEGACY_AUTOLOAD)) {
750 blk_request_module(dev);
751 inode = ilookup(blockdev_superblock, dev);
752 if (inode)
753 pr_warn_ratelimited(
754 "block device autoloading is deprecated and will be removed.\n");
755 }
756 if (!inode)
757 return NULL;
758
759 /* switch from the inode reference to a device mode one: */
760 bdev = &BDEV_I(inode)->bdev;
761 if (!kobject_get_unless_zero(&bdev->bd_device.kobj))
762 bdev = NULL;
763 iput(inode);
764 return bdev;
765 }
766
blkdev_put_no_open(struct block_device * bdev)767 void blkdev_put_no_open(struct block_device *bdev)
768 {
769 put_device(&bdev->bd_device);
770 }
771
772 /**
773 * blkdev_get_by_dev - open a block device by device number
774 * @dev: device number of block device to open
775 * @mode: FMODE_* mask
776 * @holder: exclusive holder identifier
777 *
778 * Open the block device described by device number @dev. If @mode includes
779 * %FMODE_EXCL, the block device is opened with exclusive access. Specifying
780 * %FMODE_EXCL with a %NULL @holder is invalid. Exclusive opens may nest for
781 * the same @holder.
782 *
783 * Use this interface ONLY if you really do not have anything better - i.e. when
784 * you are behind a truly sucky interface and all you are given is a device
785 * number. Everything else should use blkdev_get_by_path().
786 *
787 * CONTEXT:
788 * Might sleep.
789 *
790 * RETURNS:
791 * Reference to the block_device on success, ERR_PTR(-errno) on failure.
792 */
blkdev_get_by_dev(dev_t dev,fmode_t mode,void * holder)793 struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode, void *holder)
794 {
795 bool unblock_events = true;
796 struct block_device *bdev;
797 struct gendisk *disk;
798 int ret;
799
800 ret = devcgroup_check_permission(DEVCG_DEV_BLOCK,
801 MAJOR(dev), MINOR(dev),
802 ((mode & FMODE_READ) ? DEVCG_ACC_READ : 0) |
803 ((mode & FMODE_WRITE) ? DEVCG_ACC_WRITE : 0));
804 if (ret)
805 return ERR_PTR(ret);
806
807 bdev = blkdev_get_no_open(dev);
808 if (!bdev)
809 return ERR_PTR(-ENXIO);
810 disk = bdev->bd_disk;
811
812 if (mode & FMODE_EXCL) {
813 ret = bd_prepare_to_claim(bdev, holder);
814 if (ret)
815 goto put_blkdev;
816 }
817
818 disk_block_events(disk);
819
820 mutex_lock(&disk->open_mutex);
821 ret = -ENXIO;
822 if (!disk_live(disk))
823 goto abort_claiming;
824 if (!try_module_get(disk->fops->owner))
825 goto abort_claiming;
826 if (bdev_is_partition(bdev))
827 ret = blkdev_get_part(bdev, mode);
828 else
829 ret = blkdev_get_whole(bdev, mode);
830 if (ret)
831 goto put_module;
832 if (mode & FMODE_EXCL) {
833 bd_finish_claiming(bdev, holder);
834
835 /*
836 * Block event polling for write claims if requested. Any write
837 * holder makes the write_holder state stick until all are
838 * released. This is good enough and tracking individual
839 * writeable reference is too fragile given the way @mode is
840 * used in blkdev_get/put().
841 */
842 if ((mode & FMODE_WRITE) && !bdev->bd_write_holder &&
843 (disk->event_flags & DISK_EVENT_FLAG_BLOCK_ON_EXCL_WRITE)) {
844 bdev->bd_write_holder = true;
845 unblock_events = false;
846 }
847 }
848 mutex_unlock(&disk->open_mutex);
849
850 if (unblock_events)
851 disk_unblock_events(disk);
852 return bdev;
853 put_module:
854 module_put(disk->fops->owner);
855 abort_claiming:
856 if (mode & FMODE_EXCL)
857 bd_abort_claiming(bdev, holder);
858 mutex_unlock(&disk->open_mutex);
859 disk_unblock_events(disk);
860 put_blkdev:
861 blkdev_put_no_open(bdev);
862 return ERR_PTR(ret);
863 }
864 EXPORT_SYMBOL(blkdev_get_by_dev);
865
866 /**
867 * blkdev_get_by_path - open a block device by name
868 * @path: path to the block device to open
869 * @mode: FMODE_* mask
870 * @holder: exclusive holder identifier
871 *
872 * Open the block device described by the device file at @path. If @mode
873 * includes %FMODE_EXCL, the block device is opened with exclusive access.
874 * Specifying %FMODE_EXCL with a %NULL @holder is invalid. Exclusive opens may
875 * nest for the same @holder.
876 *
877 * CONTEXT:
878 * Might sleep.
879 *
880 * RETURNS:
881 * Reference to the block_device on success, ERR_PTR(-errno) on failure.
882 */
blkdev_get_by_path(const char * path,fmode_t mode,void * holder)883 struct block_device *blkdev_get_by_path(const char *path, fmode_t mode,
884 void *holder)
885 {
886 struct block_device *bdev;
887 dev_t dev;
888 int error;
889
890 error = lookup_bdev(path, &dev);
891 if (error)
892 return ERR_PTR(error);
893
894 bdev = blkdev_get_by_dev(dev, mode, holder);
895 if (!IS_ERR(bdev) && (mode & FMODE_WRITE) && bdev_read_only(bdev)) {
896 blkdev_put(bdev, mode);
897 return ERR_PTR(-EACCES);
898 }
899
900 return bdev;
901 }
902 EXPORT_SYMBOL(blkdev_get_by_path);
903
blkdev_put(struct block_device * bdev,fmode_t mode)904 void blkdev_put(struct block_device *bdev, fmode_t mode)
905 {
906 struct gendisk *disk = bdev->bd_disk;
907
908 /*
909 * Sync early if it looks like we're the last one. If someone else
910 * opens the block device between now and the decrement of bd_openers
911 * then we did a sync that we didn't need to, but that's not the end
912 * of the world and we want to avoid long (could be several minute)
913 * syncs while holding the mutex.
914 */
915 if (atomic_read(&bdev->bd_openers) == 1)
916 sync_blockdev(bdev);
917
918 mutex_lock(&disk->open_mutex);
919 if (mode & FMODE_EXCL) {
920 struct block_device *whole = bdev_whole(bdev);
921 bool bdev_free;
922
923 /*
924 * Release a claim on the device. The holder fields
925 * are protected with bdev_lock. open_mutex is to
926 * synchronize disk_holder unlinking.
927 */
928 spin_lock(&bdev_lock);
929
930 WARN_ON_ONCE(--bdev->bd_holders < 0);
931 WARN_ON_ONCE(--whole->bd_holders < 0);
932
933 if ((bdev_free = !bdev->bd_holders))
934 bdev->bd_holder = NULL;
935 if (!whole->bd_holders)
936 whole->bd_holder = NULL;
937
938 spin_unlock(&bdev_lock);
939
940 /*
941 * If this was the last claim, remove holder link and
942 * unblock evpoll if it was a write holder.
943 */
944 if (bdev_free && bdev->bd_write_holder) {
945 disk_unblock_events(disk);
946 bdev->bd_write_holder = false;
947 }
948 }
949
950 /*
951 * Trigger event checking and tell drivers to flush MEDIA_CHANGE
952 * event. This is to ensure detection of media removal commanded
953 * from userland - e.g. eject(1).
954 */
955 disk_flush_events(disk, DISK_EVENT_MEDIA_CHANGE);
956
957 if (bdev_is_partition(bdev))
958 blkdev_put_part(bdev, mode);
959 else
960 blkdev_put_whole(bdev, mode);
961 mutex_unlock(&disk->open_mutex);
962
963 module_put(disk->fops->owner);
964 blkdev_put_no_open(bdev);
965 }
966 EXPORT_SYMBOL(blkdev_put);
967
968 /**
969 * lookup_bdev() - Look up a struct block_device by name.
970 * @pathname: Name of the block device in the filesystem.
971 * @dev: Pointer to the block device's dev_t, if found.
972 *
973 * Lookup the block device's dev_t at @pathname in the current
974 * namespace if possible and return it in @dev.
975 *
976 * Context: May sleep.
977 * Return: 0 if succeeded, negative errno otherwise.
978 */
lookup_bdev(const char * pathname,dev_t * dev)979 int lookup_bdev(const char *pathname, dev_t *dev)
980 {
981 struct inode *inode;
982 struct path path;
983 int error;
984
985 if (!pathname || !*pathname)
986 return -EINVAL;
987
988 error = kern_path(pathname, LOOKUP_FOLLOW, &path);
989 if (error)
990 return error;
991
992 inode = d_backing_inode(path.dentry);
993 error = -ENOTBLK;
994 if (!S_ISBLK(inode->i_mode))
995 goto out_path_put;
996 error = -EACCES;
997 if (!may_open_dev(&path))
998 goto out_path_put;
999
1000 *dev = inode->i_rdev;
1001 error = 0;
1002 out_path_put:
1003 path_put(&path);
1004 return error;
1005 }
1006 EXPORT_SYMBOL(lookup_bdev);
1007
__invalidate_device(struct block_device * bdev,bool kill_dirty)1008 int __invalidate_device(struct block_device *bdev, bool kill_dirty)
1009 {
1010 struct super_block *sb = get_super(bdev);
1011 int res = 0;
1012
1013 if (sb) {
1014 /*
1015 * no need to lock the super, get_super holds the
1016 * read mutex so the filesystem cannot go away
1017 * under us (->put_super runs with the write lock
1018 * hold).
1019 */
1020 shrink_dcache_sb(sb);
1021 res = invalidate_inodes(sb, kill_dirty);
1022 drop_super(sb);
1023 }
1024 invalidate_bdev(bdev);
1025 return res;
1026 }
1027 EXPORT_SYMBOL(__invalidate_device);
1028
sync_bdevs(bool wait)1029 void sync_bdevs(bool wait)
1030 {
1031 struct inode *inode, *old_inode = NULL;
1032
1033 spin_lock(&blockdev_superblock->s_inode_list_lock);
1034 list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list) {
1035 struct address_space *mapping = inode->i_mapping;
1036 struct block_device *bdev;
1037
1038 spin_lock(&inode->i_lock);
1039 if (inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW) ||
1040 mapping->nrpages == 0) {
1041 spin_unlock(&inode->i_lock);
1042 continue;
1043 }
1044 __iget(inode);
1045 spin_unlock(&inode->i_lock);
1046 spin_unlock(&blockdev_superblock->s_inode_list_lock);
1047 /*
1048 * We hold a reference to 'inode' so it couldn't have been
1049 * removed from s_inodes list while we dropped the
1050 * s_inode_list_lock We cannot iput the inode now as we can
1051 * be holding the last reference and we cannot iput it under
1052 * s_inode_list_lock. So we keep the reference and iput it
1053 * later.
1054 */
1055 iput(old_inode);
1056 old_inode = inode;
1057 bdev = I_BDEV(inode);
1058
1059 mutex_lock(&bdev->bd_disk->open_mutex);
1060 if (!atomic_read(&bdev->bd_openers)) {
1061 ; /* skip */
1062 } else if (wait) {
1063 /*
1064 * We keep the error status of individual mapping so
1065 * that applications can catch the writeback error using
1066 * fsync(2). See filemap_fdatawait_keep_errors() for
1067 * details.
1068 */
1069 filemap_fdatawait_keep_errors(inode->i_mapping);
1070 } else {
1071 filemap_fdatawrite(inode->i_mapping);
1072 }
1073 mutex_unlock(&bdev->bd_disk->open_mutex);
1074
1075 spin_lock(&blockdev_superblock->s_inode_list_lock);
1076 }
1077 spin_unlock(&blockdev_superblock->s_inode_list_lock);
1078 iput(old_inode);
1079 }
1080
1081 /*
1082 * Handle STATX_DIOALIGN for block devices.
1083 *
1084 * Note that the inode passed to this is the inode of a block device node file,
1085 * not the block device's internal inode. Therefore it is *not* valid to use
1086 * I_BDEV() here; the block device has to be looked up by i_rdev instead.
1087 */
bdev_statx_dioalign(struct inode * inode,struct kstat * stat)1088 void bdev_statx_dioalign(struct inode *inode, struct kstat *stat)
1089 {
1090 struct block_device *bdev;
1091
1092 bdev = blkdev_get_no_open(inode->i_rdev);
1093 if (!bdev)
1094 return;
1095
1096 stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
1097 stat->dio_offset_align = bdev_logical_block_size(bdev);
1098 stat->result_mask |= STATX_DIOALIGN;
1099
1100 blkdev_put_no_open(bdev);
1101 }
1102