xref: /linux/block/fops.c (revision cb8fef4b07f71da01843457b66e579ad248a625e)
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 #include <linux/init.h>
8 #include <linux/mm.h>
9 #include <linux/blkdev.h>
10 #include <linux/blk-integrity.h>
11 #include <linux/buffer_head.h>
12 #include <linux/mpage.h>
13 #include <linux/uio.h>
14 #include <linux/namei.h>
15 #include <linux/task_io_accounting_ops.h>
16 #include <linux/falloc.h>
17 #include <linux/suspend.h>
18 #include <linux/fs.h>
19 #include <linux/iomap.h>
20 #include <linux/module.h>
21 #include <linux/io_uring/cmd.h>
22 #include "blk.h"
23 
24 static inline struct inode *bdev_file_inode(struct file *file)
25 {
26 	return file->f_mapping->host;
27 }
28 
29 static bool blkdev_dio_fua(struct kiocb *iocb, struct block_device *bdev)
30 {
31 	if (!iocb_is_dsync(iocb))
32 		return false;
33 	/*
34 	 * Async writes cannot fall back to generic_write_sync(), so they must
35 	 * use FUA (emulated if needed); sync writes only need it when the
36 	 * device supports FUA natively.
37 	 */
38 	if (!is_sync_kiocb(iocb))
39 		return true;
40 	return bdev_fua(bdev);
41 }
42 
43 static blk_opf_t dio_bio_write_op(struct kiocb *iocb, struct block_device *bdev)
44 {
45 	blk_opf_t opf = REQ_OP_WRITE | REQ_SYNC | REQ_IDLE;
46 
47 	/* avoid the need for a I/O completion work item */
48 	if (blkdev_dio_fua(iocb, bdev))
49 		opf |= REQ_FUA;
50 	return opf;
51 }
52 
53 static bool blkdev_dio_invalid(struct block_device *bdev, struct kiocb *iocb,
54 				struct iov_iter *iter)
55 {
56 	return (iocb->ki_pos | iov_iter_count(iter)) &
57 			(bdev_logical_block_size(bdev) - 1);
58 }
59 
60 static inline int blkdev_iov_iter_get_pages(struct bio *bio,
61 		struct iov_iter *iter, struct block_device *bdev)
62 {
63 	return bio_iov_iter_get_pages(bio, iter, BIO_MAX_SIZE,
64 			bdev_dma_alignment(bdev),
65 			bdev_logical_block_size(bdev) - 1);
66 }
67 
68 #define DIO_INLINE_BIO_VECS 4
69 
70 static ssize_t __blkdev_direct_IO_simple(struct kiocb *iocb,
71 		struct iov_iter *iter, struct block_device *bdev,
72 		unsigned int nr_pages)
73 {
74 	struct bio_vec inline_vecs[DIO_INLINE_BIO_VECS], *vecs;
75 	loff_t pos = iocb->ki_pos;
76 	bool should_dirty = false;
77 	struct bio bio;
78 	ssize_t ret;
79 
80 	if (nr_pages <= DIO_INLINE_BIO_VECS)
81 		vecs = inline_vecs;
82 	else {
83 		vecs = kmalloc_objs(struct bio_vec, nr_pages);
84 		if (!vecs)
85 			return -ENOMEM;
86 	}
87 
88 	if (iov_iter_rw(iter) == READ) {
89 		bio_init(&bio, bdev, vecs, nr_pages, REQ_OP_READ);
90 		if (user_backed_iter(iter))
91 			should_dirty = true;
92 	} else {
93 		bio_init(&bio, bdev, vecs, nr_pages,
94 			 dio_bio_write_op(iocb, bdev));
95 	}
96 	bio.bi_iter.bi_sector = pos >> SECTOR_SHIFT;
97 	bio.bi_write_hint = file_inode(iocb->ki_filp)->i_write_hint;
98 	bio.bi_write_stream = iocb->ki_write_stream;
99 	bio.bi_ioprio = iocb->ki_ioprio;
100 	if (iocb->ki_flags & IOCB_ATOMIC)
101 		bio.bi_opf |= REQ_ATOMIC;
102 
103 	ret = blkdev_iov_iter_get_pages(&bio, iter, bdev);
104 	if (unlikely(ret))
105 		goto out;
106 	ret = bio.bi_iter.bi_size;
107 
108 	if (iov_iter_rw(iter) == WRITE)
109 		task_io_account_write(ret);
110 
111 	if (iocb->ki_flags & IOCB_NOWAIT)
112 		bio.bi_opf |= REQ_NOWAIT;
113 
114 	submit_bio_wait(&bio);
115 
116 	bio_release_pages(&bio, should_dirty);
117 	if (unlikely(bio.bi_status))
118 		ret = blk_status_to_errno(bio.bi_status);
119 
120 out:
121 	if (vecs != inline_vecs)
122 		kfree(vecs);
123 
124 	bio_uninit(&bio);
125 
126 	return ret;
127 }
128 
129 enum {
130 	DIO_SHOULD_DIRTY	= 1,
131 	DIO_IS_SYNC		= 2,
132 };
133 
134 struct blkdev_dio {
135 	union {
136 		struct kiocb		*iocb;
137 		struct task_struct	*waiter;
138 	};
139 	size_t			size;
140 	atomic_t		ref;
141 	unsigned int		flags;
142 	struct bio		bio ____cacheline_aligned_in_smp;
143 };
144 
145 static struct bio_set blkdev_dio_pool;
146 
147 static void blkdev_bio_end_io(struct bio *bio)
148 {
149 	struct blkdev_dio *dio = bio->bi_private;
150 	bool should_dirty = dio->flags & DIO_SHOULD_DIRTY;
151 	bool is_sync = dio->flags & DIO_IS_SYNC;
152 
153 	if (bio->bi_status && !dio->bio.bi_status)
154 		dio->bio.bi_status = bio->bi_status;
155 
156 	if (bio_integrity(bio))
157 		bio_integrity_unmap_user(bio);
158 
159 	if (atomic_dec_and_test(&dio->ref)) {
160 		if (!is_sync) {
161 			struct kiocb *iocb = dio->iocb;
162 			ssize_t ret;
163 
164 			WRITE_ONCE(iocb->private, NULL);
165 
166 			if (likely(!dio->bio.bi_status)) {
167 				ret = dio->size;
168 				iocb->ki_pos += ret;
169 			} else {
170 				ret = blk_status_to_errno(dio->bio.bi_status);
171 			}
172 
173 			dio->iocb->ki_complete(iocb, ret);
174 			bio_put(&dio->bio);
175 		} else {
176 			struct task_struct *waiter = dio->waiter;
177 
178 			WRITE_ONCE(dio->waiter, NULL);
179 			blk_wake_io_task(waiter);
180 		}
181 	}
182 
183 	if (should_dirty) {
184 		bio_check_pages_dirty(bio);
185 	} else {
186 		bio_release_pages(bio, false);
187 		bio_put(bio);
188 	}
189 }
190 
191 static ssize_t __blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
192 		struct block_device *bdev, unsigned int nr_pages)
193 {
194 	struct blk_plug plug;
195 	struct blkdev_dio *dio;
196 	struct bio *bio;
197 	bool is_read = (iov_iter_rw(iter) == READ), is_sync;
198 	blk_opf_t opf = is_read ? REQ_OP_READ : dio_bio_write_op(iocb, bdev);
199 	loff_t pos = iocb->ki_pos;
200 	int ret = 0;
201 
202 	bio = bio_alloc_bioset(bdev, nr_pages, opf, GFP_KERNEL,
203 			       &blkdev_dio_pool);
204 	dio = container_of(bio, struct blkdev_dio, bio);
205 	atomic_set(&dio->ref, 1);
206 	/*
207 	 * Grab an extra reference to ensure the dio structure which is embedded
208 	 * into the first bio stays around.
209 	 */
210 	bio_get(bio);
211 
212 	is_sync = is_sync_kiocb(iocb);
213 	if (is_sync) {
214 		dio->flags = DIO_IS_SYNC;
215 		dio->waiter = current;
216 	} else {
217 		dio->flags = 0;
218 		dio->iocb = iocb;
219 	}
220 
221 	dio->size = 0;
222 	if (is_read && user_backed_iter(iter))
223 		dio->flags |= DIO_SHOULD_DIRTY;
224 
225 	blk_start_plug(&plug);
226 
227 	for (;;) {
228 		bio->bi_iter.bi_sector = pos >> SECTOR_SHIFT;
229 		bio->bi_write_hint = file_inode(iocb->ki_filp)->i_write_hint;
230 		bio->bi_write_stream = iocb->ki_write_stream;
231 		bio->bi_private = dio;
232 		bio->bi_end_io = blkdev_bio_end_io;
233 		bio->bi_ioprio = iocb->ki_ioprio;
234 
235 		ret = blkdev_iov_iter_get_pages(bio, iter, bdev);
236 		if (unlikely(ret)) {
237 			bio_endio_status(bio, errno_to_blk_status(ret));
238 			break;
239 		}
240 		if (iocb->ki_flags & IOCB_NOWAIT) {
241 			/*
242 			 * This is nonblocking IO, and we need to allocate
243 			 * another bio if we have data left to map. As we
244 			 * cannot guarantee that one of the sub bios will not
245 			 * fail getting issued FOR NOWAIT and as error results
246 			 * are coalesced across all of them, be safe and ask for
247 			 * a retry of this from blocking context.
248 			 */
249 			if (unlikely(iov_iter_count(iter))) {
250 				ret = -EAGAIN;
251 				goto fail;
252 			}
253 			bio->bi_opf |= REQ_NOWAIT;
254 		}
255 		if (iocb->ki_flags & IOCB_HAS_METADATA) {
256 			ret = bio_integrity_map_iter(bio, iocb->private);
257 			if (unlikely(ret)) {
258 				bio_endio_status(bio, errno_to_blk_status(ret));
259 				break;
260 			}
261 		}
262 
263 		if (is_read) {
264 			if (dio->flags & DIO_SHOULD_DIRTY)
265 				bio_set_pages_dirty(bio);
266 		} else {
267 			task_io_account_write(bio->bi_iter.bi_size);
268 		}
269 		dio->size += bio->bi_iter.bi_size;
270 		pos += bio->bi_iter.bi_size;
271 
272 		nr_pages = bio_iov_vecs_to_alloc(iter, BIO_MAX_VECS);
273 		if (!nr_pages) {
274 			submit_bio(bio);
275 			break;
276 		}
277 		atomic_inc(&dio->ref);
278 		submit_bio(bio);
279 		bio = bio_alloc(bdev, nr_pages, opf, GFP_KERNEL);
280 	}
281 
282 	blk_finish_plug(&plug);
283 
284 	if (!is_sync)
285 		return -EIOCBQUEUED;
286 
287 	for (;;) {
288 		set_current_state(TASK_UNINTERRUPTIBLE);
289 		if (!READ_ONCE(dio->waiter))
290 			break;
291 		blk_io_schedule();
292 	}
293 	__set_current_state(TASK_RUNNING);
294 
295 	if (!ret)
296 		ret = blk_status_to_errno(dio->bio.bi_status);
297 	if (likely(!ret))
298 		ret = dio->size;
299 
300 	bio_put(&dio->bio);
301 	return ret;
302 fail:
303 	bio_release_pages(bio, false);
304 	bio_clear_flag(bio, BIO_REFFED);
305 	bio_put(bio);
306 	blk_finish_plug(&plug);
307 	return ret;
308 }
309 
310 static void blkdev_bio_end_io_async(struct bio *bio)
311 {
312 	struct blkdev_dio *dio = container_of(bio, struct blkdev_dio, bio);
313 	struct kiocb *iocb = dio->iocb;
314 	ssize_t ret;
315 
316 	WRITE_ONCE(iocb->private, NULL);
317 
318 	if (likely(!bio->bi_status)) {
319 		ret = dio->size;
320 		iocb->ki_pos += ret;
321 	} else {
322 		ret = blk_status_to_errno(bio->bi_status);
323 	}
324 
325 	iocb->ki_complete(iocb, ret);
326 
327 	if (dio->flags & DIO_SHOULD_DIRTY) {
328 		bio_check_pages_dirty(bio);
329 	} else {
330 		bio_release_pages(bio, false);
331 		bio_put(bio);
332 	}
333 }
334 
335 static ssize_t __blkdev_direct_IO_async(struct kiocb *iocb,
336 					struct iov_iter *iter,
337 					struct block_device *bdev,
338 					unsigned int nr_pages)
339 {
340 	bool is_read = iov_iter_rw(iter) == READ;
341 	blk_opf_t opf = is_read ? REQ_OP_READ : dio_bio_write_op(iocb, bdev);
342 	struct blkdev_dio *dio;
343 	struct bio *bio;
344 	loff_t pos = iocb->ki_pos;
345 	int ret = 0;
346 
347 	bio = bio_alloc_bioset(bdev, nr_pages, opf, GFP_KERNEL,
348 			       &blkdev_dio_pool);
349 	dio = container_of(bio, struct blkdev_dio, bio);
350 	dio->flags = 0;
351 	dio->iocb = iocb;
352 	bio->bi_iter.bi_sector = pos >> SECTOR_SHIFT;
353 	bio->bi_write_hint = file_inode(iocb->ki_filp)->i_write_hint;
354 	bio->bi_write_stream = iocb->ki_write_stream;
355 	bio->bi_end_io = blkdev_bio_end_io_async;
356 	bio->bi_ioprio = iocb->ki_ioprio;
357 
358 	if (iocb->ki_flags & IOCB_ATOMIC)
359 		bio->bi_opf |= REQ_ATOMIC;
360 
361 	if (iocb->ki_flags & IOCB_NOWAIT)
362 		bio->bi_opf |= REQ_NOWAIT;
363 
364 	/*
365 	 * Users don't rely on the iterator being in any particular
366 	 * state for async I/O returning -EIOCBQUEUED, hence we can
367 	 * avoid expensive iov_iter_advance(). Bypass
368 	 * bio_iov_iter_get_pages() and set the bvec directly.
369 	 */
370 	if (!bio_iov_iter_set(bio, iter)) {
371 		ret = blkdev_iov_iter_get_pages(bio, iter, bdev);
372 		if (unlikely(ret))
373 			goto out_bio_put;
374 	}
375 	dio->size = bio->bi_iter.bi_size;
376 
377 	if (is_read) {
378 		if (user_backed_iter(iter)) {
379 			dio->flags |= DIO_SHOULD_DIRTY;
380 			bio_set_pages_dirty(bio);
381 		}
382 	} else {
383 		task_io_account_write(bio->bi_iter.bi_size);
384 	}
385 
386 	if (iocb->ki_flags & IOCB_HIPRI) {
387 		bio->bi_opf |= REQ_POLLED;
388 		submit_bio(bio);
389 		WRITE_ONCE(iocb->private, bio);
390 	} else {
391 		submit_bio(bio);
392 	}
393 	return -EIOCBQUEUED;
394 
395 out_bio_put:
396 	bio_put(bio);
397 	return ret;
398 }
399 
400 static ssize_t blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
401 {
402 	struct block_device *bdev = I_BDEV(iocb->ki_filp->f_mapping->host);
403 	unsigned int nr_pages;
404 
405 	if (!iov_iter_count(iter))
406 		return 0;
407 
408 	if (blkdev_dio_invalid(bdev, iocb, iter))
409 		return -EINVAL;
410 
411 	/* HIPRI needs private as bio; HAS_METADATA keeps it as uio_meta */
412 	if ((iocb->ki_flags & IOCB_HIPRI) &&
413 	    (iocb->ki_flags & IOCB_HAS_METADATA))
414 		return -EOPNOTSUPP;
415 
416 	if (iov_iter_rw(iter) == WRITE) {
417 		u16 max_write_streams = bdev_max_write_streams(bdev);
418 
419 		if (iocb->ki_write_stream) {
420 			if (iocb->ki_write_stream > max_write_streams)
421 				return -EINVAL;
422 		} else if (max_write_streams) {
423 			enum rw_hint write_hint =
424 				file_inode(iocb->ki_filp)->i_write_hint;
425 
426 			/*
427 			 * Just use the write hint as write stream for block
428 			 * device writes.  This assumes no file system is
429 			 * mounted that would use the streams differently.
430 			 */
431 			if (write_hint <= max_write_streams)
432 				iocb->ki_write_stream = write_hint;
433 		}
434 	}
435 
436 	nr_pages = bio_iov_vecs_to_alloc(iter, BIO_MAX_VECS + 1);
437 	if (likely(nr_pages <= BIO_MAX_VECS &&
438 		   !(iocb->ki_flags & IOCB_HAS_METADATA))) {
439 		if (is_sync_kiocb(iocb))
440 			return __blkdev_direct_IO_simple(iocb, iter, bdev,
441 							nr_pages);
442 		return __blkdev_direct_IO_async(iocb, iter, bdev, nr_pages);
443 	} else if (iocb->ki_flags & IOCB_ATOMIC) {
444 		return -EINVAL;
445 	}
446 	return __blkdev_direct_IO(iocb, iter, bdev, bio_max_segs(nr_pages));
447 }
448 
449 static int blkdev_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
450 		unsigned int flags, struct iomap *iomap, struct iomap *srcmap)
451 {
452 	struct block_device *bdev = I_BDEV(inode);
453 	loff_t isize = i_size_read(inode);
454 
455 	if (offset >= isize)
456 		return -EIO;
457 
458 	iomap->bdev = bdev;
459 	iomap->offset = ALIGN_DOWN(offset, bdev_logical_block_size(bdev));
460 	iomap->type = IOMAP_MAPPED;
461 	iomap->addr = iomap->offset;
462 	iomap->length = isize - iomap->offset;
463 	iomap->flags |= IOMAP_F_BUFFER_HEAD; /* noop for !CONFIG_BUFFER_HEAD */
464 	return 0;
465 }
466 
467 static DEFINE_IOMAP_ITER_NEXT(blkdev_iomap_next, blkdev_iomap_begin);
468 
469 static const struct iomap_ops blkdev_iomap_ops = {
470 	.iomap_next		= blkdev_iomap_next,
471 };
472 
473 #ifdef CONFIG_BUFFER_HEAD
474 static int blkdev_get_block(struct inode *inode, sector_t iblock,
475 		struct buffer_head *bh, int create)
476 {
477 	bh->b_bdev = I_BDEV(inode);
478 	bh->b_blocknr = iblock;
479 	set_buffer_mapped(bh);
480 	return 0;
481 }
482 
483 /*
484  * We cannot call mpage_writepages() as it does not take the buffer lock.
485  * We must use block_write_full_folio() directly which holds the buffer
486  * lock.  The buffer lock provides the synchronisation with writeback
487  * that filesystems rely on when they use the blockdev's mapping.
488  */
489 static int blkdev_writepages(struct address_space *mapping,
490 		struct writeback_control *wbc)
491 {
492 	struct folio *folio = NULL;
493 	struct blk_plug plug;
494 	int err;
495 
496 	blk_start_plug(&plug);
497 	while ((folio = writeback_iter(mapping, wbc, folio, &err)))
498 		err = block_write_full_folio(folio, wbc, blkdev_get_block);
499 	blk_finish_plug(&plug);
500 
501 	return err;
502 }
503 
504 static int blkdev_read_folio(struct file *file, struct folio *folio)
505 {
506 	return block_read_full_folio(folio, blkdev_get_block);
507 }
508 
509 static void blkdev_readahead(struct readahead_control *rac)
510 {
511 	mpage_readahead(rac, blkdev_get_block);
512 }
513 
514 const struct address_space_operations def_blk_aops = {
515 	.dirty_folio	= block_dirty_folio,
516 	.invalidate_folio = block_invalidate_folio,
517 	.read_folio	= blkdev_read_folio,
518 	.readahead	= blkdev_readahead,
519 	.writepages	= blkdev_writepages,
520 	.migrate_folio	= buffer_migrate_folio_norefs,
521 	.is_dirty_writeback = buffer_check_dirty_writeback,
522 };
523 #else /* CONFIG_BUFFER_HEAD */
524 static int blkdev_read_folio(struct file *file, struct folio *folio)
525 {
526 	iomap_bio_read_folio(folio, &blkdev_iomap_ops);
527 	return 0;
528 }
529 
530 static void blkdev_readahead(struct readahead_control *rac)
531 {
532 	iomap_bio_readahead(rac, &blkdev_iomap_ops);
533 }
534 
535 static ssize_t blkdev_writeback_range(struct iomap_writepage_ctx *wpc,
536 		struct folio *folio, u64 offset, unsigned int len, u64 end_pos)
537 {
538 	loff_t isize = i_size_read(wpc->inode);
539 
540 	if (WARN_ON_ONCE(offset >= isize))
541 		return -EIO;
542 
543 	if (offset < wpc->iomap.offset ||
544 	    offset >= wpc->iomap.offset + wpc->iomap.length) {
545 		int error;
546 
547 		error = blkdev_iomap_begin(wpc->inode, offset, isize - offset,
548 				IOMAP_WRITE, &wpc->iomap, NULL);
549 		if (error)
550 			return error;
551 	}
552 
553 	return iomap_add_to_ioend(wpc, folio, offset, end_pos, len);
554 }
555 
556 static const struct iomap_writeback_ops blkdev_writeback_ops = {
557 	.writeback_range	= blkdev_writeback_range,
558 	.writeback_submit	= iomap_ioend_writeback_submit,
559 };
560 
561 static int blkdev_writepages(struct address_space *mapping,
562 		struct writeback_control *wbc)
563 {
564 	struct iomap_writepage_ctx wpc = {
565 		.inode		= mapping->host,
566 		.wbc		= wbc,
567 		.ops		= &blkdev_writeback_ops
568 	};
569 
570 	return iomap_writepages(&wpc);
571 }
572 
573 const struct address_space_operations def_blk_aops = {
574 	.dirty_folio		= iomap_dirty_folio,
575 	.release_folio		= iomap_release_folio,
576 	.invalidate_folio	= iomap_invalidate_folio,
577 	.read_folio		= blkdev_read_folio,
578 	.readahead		= blkdev_readahead,
579 	.writepages		= blkdev_writepages,
580 	.is_partially_uptodate  = iomap_is_partially_uptodate,
581 	.error_remove_folio	= generic_error_remove_folio,
582 	.migrate_folio		= filemap_migrate_folio,
583 };
584 #endif /* CONFIG_BUFFER_HEAD */
585 
586 /*
587  * for a block special file file_inode(file)->i_size is zero
588  * so we compute the size by hand (just as in block_read/write above)
589  */
590 static loff_t blkdev_llseek(struct file *file, loff_t offset, int whence)
591 {
592 	struct inode *bd_inode = bdev_file_inode(file);
593 	loff_t retval;
594 
595 	inode_lock(bd_inode);
596 	retval = fixed_size_llseek(file, offset, whence, i_size_read(bd_inode));
597 	inode_unlock(bd_inode);
598 	return retval;
599 }
600 
601 static int blkdev_fsync(struct file *filp, loff_t start, loff_t end,
602 		int datasync)
603 {
604 	struct block_device *bdev = I_BDEV(filp->f_mapping->host);
605 	int error;
606 
607 	error = file_write_and_wait_range(filp, start, end);
608 	if (error)
609 		return error;
610 
611 	/*
612 	 * There is no need to serialise calls to blkdev_issue_flush with
613 	 * i_mutex and doing so causes performance issues with concurrent
614 	 * O_SYNC writers to a block device.
615 	 */
616 	error = blkdev_issue_flush(bdev);
617 	if (error == -EOPNOTSUPP)
618 		error = 0;
619 
620 	return error;
621 }
622 
623 /**
624  * file_to_blk_mode - get block open flags from file flags
625  * @file: file whose open flags should be converted
626  *
627  * Look at file open flags and generate corresponding block open flags from
628  * them. The function works both for file just being open (e.g. during ->open
629  * callback) and for file that is already open. This is actually non-trivial
630  * (see comment in the function).
631  */
632 blk_mode_t file_to_blk_mode(struct file *file)
633 {
634 	blk_mode_t mode = 0;
635 
636 	if (file->f_mode & FMODE_READ)
637 		mode |= BLK_OPEN_READ;
638 	if (file->f_mode & FMODE_WRITE)
639 		mode |= BLK_OPEN_WRITE;
640 	/*
641 	 * do_dentry_open() clears O_EXCL from f_flags, use file->private_data
642 	 * to determine whether the open was exclusive for already open files.
643 	 */
644 	if (file->private_data)
645 		mode |= BLK_OPEN_EXCL;
646 	else if (file->f_flags & O_EXCL)
647 		mode |= BLK_OPEN_EXCL;
648 	if (file->f_flags & O_NDELAY)
649 		mode |= BLK_OPEN_NDELAY;
650 
651 	/*
652 	 * If all bits in O_ACCMODE set (aka O_RDWR | O_WRONLY), the floppy
653 	 * driver has historically allowed ioctls as if the file was opened for
654 	 * writing, but does not allow and actual reads or writes.
655 	 */
656 	if ((file->f_flags & O_ACCMODE) == (O_RDWR | O_WRONLY))
657 		mode |= BLK_OPEN_WRITE_IOCTL;
658 
659 	return mode;
660 }
661 
662 static int blkdev_open(struct inode *inode, struct file *filp)
663 {
664 	struct block_device *bdev;
665 	blk_mode_t mode;
666 	int ret;
667 
668 	mode = file_to_blk_mode(filp);
669 	/* Use the file as the holder. */
670 	if (mode & BLK_OPEN_EXCL)
671 		filp->private_data = filp;
672 	ret = bdev_permission(inode->i_rdev, mode, filp->private_data);
673 	if (ret)
674 		return ret;
675 
676 	bdev = blkdev_get_no_open(inode->i_rdev, true);
677 	if (!bdev)
678 		return -ENXIO;
679 
680 	if (bdev_can_atomic_write(bdev))
681 		filp->f_mode |= FMODE_CAN_ATOMIC_WRITE;
682 	if (blk_get_integrity(bdev->bd_disk))
683 		filp->f_mode |= FMODE_HAS_METADATA;
684 
685 	ret = bdev_open(bdev, mode, filp->private_data, NULL, filp);
686 	if (ret)
687 		blkdev_put_no_open(bdev);
688 	return ret;
689 }
690 
691 static int blkdev_release(struct inode *inode, struct file *filp)
692 {
693 	bdev_release(filp);
694 	return 0;
695 }
696 
697 static ssize_t
698 blkdev_direct_write(struct kiocb *iocb, struct iov_iter *from)
699 {
700 	size_t count = iov_iter_count(from);
701 	ssize_t written;
702 
703 	written = kiocb_invalidate_pages(iocb, count);
704 	if (written) {
705 		if (written == -EBUSY)
706 			return 0;
707 		return written;
708 	}
709 
710 	written = blkdev_direct_IO(iocb, from);
711 	if (written > 0) {
712 		kiocb_invalidate_post_direct_write(iocb, count);
713 		iocb->ki_pos += written;
714 		count -= written;
715 	}
716 	if (written != -EIOCBQUEUED)
717 		iov_iter_revert(from, count - iov_iter_count(from));
718 	return written;
719 }
720 
721 static ssize_t blkdev_buffered_write(struct kiocb *iocb, struct iov_iter *from)
722 {
723 	struct inode *inode = bdev_file_inode(iocb->ki_filp);
724 	ssize_t ret;
725 
726 	/* Buffered fallback waits for writeback, which NOWAIT cannot allow. */
727 	if (iocb->ki_flags & IOCB_NOWAIT)
728 		return -EAGAIN;
729 
730 	/*
731 	 * Take i_rwsem to avoid racing with set_blocksize() changing
732 	 * i_blkbits/folio order and truncating the page cache.
733 	 */
734 	inode_lock_shared(inode);
735 	ret = iomap_file_buffered_write(iocb, from, &blkdev_iomap_ops, NULL,
736 					NULL);
737 	inode_unlock_shared(inode);
738 	return ret;
739 }
740 
741 /*
742  * Write data to the block device.  Only intended for the block device itself
743  * and the raw driver which basically is a fake block device.
744  *
745  * Does not take i_mutex for the write and thus is not for general purpose
746  * use.
747  */
748 static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
749 {
750 	struct file *file = iocb->ki_filp;
751 	struct inode *bd_inode = bdev_file_inode(file);
752 	struct block_device *bdev = I_BDEV(bd_inode);
753 	bool atomic = iocb->ki_flags & IOCB_ATOMIC;
754 	loff_t size = bdev_nr_bytes(bdev);
755 	size_t shorted = 0;
756 	bool need_sync = false;
757 	ssize_t ret;
758 
759 	if (bdev_read_only(bdev))
760 		return -EPERM;
761 
762 	if (IS_SWAPFILE(bd_inode) && !is_hibernate_resume_dev(bd_inode->i_rdev))
763 		return -ETXTBSY;
764 
765 	if (!iov_iter_count(from))
766 		return 0;
767 
768 	if (iocb->ki_pos >= size)
769 		return -ENOSPC;
770 
771 	if ((iocb->ki_flags & (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT)
772 		return -EOPNOTSUPP;
773 
774 	if (atomic) {
775 		ret = generic_atomic_write_valid(iocb, from);
776 		if (ret)
777 			return ret;
778 	}
779 
780 	size -= iocb->ki_pos;
781 	if (iov_iter_count(from) > size) {
782 		if (atomic)
783 			return -EINVAL;
784 		shorted = iov_iter_count(from) - size;
785 		iov_iter_truncate(from, size);
786 	}
787 
788 	ret = file_update_time(file);
789 	if (ret)
790 		return ret;
791 
792 	if (iocb->ki_flags & IOCB_DIRECT) {
793 		ret = blkdev_direct_write(iocb, from);
794 		if (ret >= 0 && iov_iter_count(from)) {
795 			if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_ATOMIC)) {
796 				/*
797 				 * The buffered fallback blocks on i_rwsem and
798 				 * on writeback of the data it copied, and
799 				 * can't provide torn-write protection: return
800 				 * the short direct write instead and let the
801 				 * caller retry. The bytes already written
802 				 * still need a flush if REQ_FUA was not set.
803 				 */
804 				if (!ret)
805 					ret = -EAGAIN;
806 				else if (!blkdev_dio_fua(iocb, bdev))
807 					need_sync = true;
808 			} else {
809 				ssize_t ret2;
810 
811 				inode_lock_shared(bd_inode);
812 				ret2 = blkdev_buffered_write(iocb, from);
813 				inode_unlock_shared(bd_inode);
814 				ret = direct_write_fallback(iocb, from, ret,
815 							    ret2);
816 				need_sync = true;
817 			}
818 		} else if (ret > 0 && !blkdev_dio_fua(iocb, bdev)) {
819 			/*
820 			 * The device does not support FUA, so REQ_FUA was not
821 			 * set and the O_DSYNC direct write still needs a flush
822 			 * to be made durable.
823 			 */
824 			need_sync = true;
825 		}
826 	} else {
827 		ret = blkdev_buffered_write(iocb, from);
828 		need_sync = true;
829 	}
830 
831 	if (ret > 0 && need_sync)
832 		ret = generic_write_sync(iocb, ret);
833 	iov_iter_reexpand(from, iov_iter_count(from) + shorted);
834 	return ret;
835 }
836 
837 static ssize_t blkdev_read_iter(struct kiocb *iocb, struct iov_iter *to)
838 {
839 	struct inode *bd_inode = bdev_file_inode(iocb->ki_filp);
840 	struct block_device *bdev = I_BDEV(iocb->ki_filp->f_mapping->host);
841 	loff_t size = bdev_nr_bytes(bdev);
842 	loff_t pos = iocb->ki_pos;
843 	size_t shorted = 0;
844 	ssize_t ret = 0;
845 	size_t count;
846 
847 	if (unlikely(pos + iov_iter_count(to) > size)) {
848 		if (pos >= size)
849 			return 0;
850 		size -= pos;
851 		shorted = iov_iter_count(to) - size;
852 		iov_iter_truncate(to, size);
853 	}
854 
855 	count = iov_iter_count(to);
856 	if (!count)
857 		goto reexpand; /* skip atime */
858 
859 	if (iocb->ki_flags & IOCB_DIRECT) {
860 		ret = kiocb_write_and_wait(iocb, count);
861 		if (ret < 0)
862 			goto reexpand;
863 		file_accessed(iocb->ki_filp);
864 
865 		ret = blkdev_direct_IO(iocb, to);
866 		if (ret > 0) {
867 			iocb->ki_pos += ret;
868 			count -= ret;
869 		}
870 		if (ret != -EIOCBQUEUED)
871 			iov_iter_revert(to, count - iov_iter_count(to));
872 		if (ret < 0 || !count)
873 			goto reexpand;
874 	}
875 
876 	/*
877 	 * Take i_rwsem and invalidate_lock to avoid racing with set_blocksize
878 	 * changing i_blkbits/folio order and punching out the pagecache.
879 	 */
880 	if (iocb->ki_flags & IOCB_NOWAIT) {
881 		if (!inode_trylock_shared(bd_inode)) {
882 			if (!ret)
883 				ret = -EAGAIN;
884 			goto reexpand;
885 		}
886 	} else {
887 		inode_lock_shared(bd_inode);
888 	}
889 	ret = filemap_read(iocb, to, ret);
890 	inode_unlock_shared(bd_inode);
891 
892 reexpand:
893 	if (unlikely(shorted))
894 		iov_iter_reexpand(to, iov_iter_count(to) + shorted);
895 	return ret;
896 }
897 
898 /*
899  * Take i_rwsem to avoid racing with set_blocksize changing i_blkbits/folio
900  * order and punching out the pagecache.
901  */
902 static ssize_t blkdev_splice_read(struct file *in, loff_t *ppos,
903 		struct pipe_inode_info *pipe, size_t len, unsigned int flags)
904 {
905 	struct inode *bd_inode = bdev_file_inode(in);
906 	ssize_t ret;
907 
908 	inode_lock_shared(bd_inode);
909 	ret = filemap_splice_read(in, ppos, pipe, len, flags);
910 	inode_unlock_shared(bd_inode);
911 	return ret;
912 }
913 
914 #define	BLKDEV_FALLOC_FL_SUPPORTED					\
915 		(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |		\
916 		 FALLOC_FL_ZERO_RANGE | FALLOC_FL_WRITE_ZEROES)
917 
918 static long blkdev_fallocate(struct file *file, int mode, loff_t start,
919 			     loff_t len)
920 {
921 	struct inode *inode = bdev_file_inode(file);
922 	struct block_device *bdev = I_BDEV(inode);
923 	loff_t end = start + len - 1;
924 	loff_t isize;
925 	unsigned int flags;
926 	int error;
927 
928 	/* Fail if we don't recognize the flags. */
929 	if (mode & ~BLKDEV_FALLOC_FL_SUPPORTED)
930 		return -EOPNOTSUPP;
931 	/*
932 	 * Don't allow writing zeroes if the device does not enable the
933 	 * unmap write zeroes operation.
934 	 */
935 	if ((mode & FALLOC_FL_WRITE_ZEROES) &&
936 	    !bdev_write_zeroes_unmap_sectors(bdev))
937 		return -EOPNOTSUPP;
938 
939 	/* Don't go off the end of the device. */
940 	isize = bdev_nr_bytes(bdev);
941 	if (start >= isize)
942 		return -EINVAL;
943 	if (end >= isize) {
944 		if (mode & FALLOC_FL_KEEP_SIZE) {
945 			len = isize - start;
946 			end = start + len - 1;
947 		} else
948 			return -EINVAL;
949 	}
950 
951 	/*
952 	 * Don't allow IO that isn't aligned to logical block size.
953 	 */
954 	if ((start | len) & (bdev_logical_block_size(bdev) - 1))
955 		return -EINVAL;
956 
957 	inode_lock(inode);
958 	filemap_invalidate_lock(inode->i_mapping);
959 
960 	switch (mode) {
961 	case FALLOC_FL_ZERO_RANGE:
962 	case FALLOC_FL_ZERO_RANGE | FALLOC_FL_KEEP_SIZE:
963 		flags = BLKDEV_ZERO_NOUNMAP;
964 		break;
965 	case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE:
966 		flags = BLKDEV_ZERO_NOFALLBACK;
967 		break;
968 	case FALLOC_FL_WRITE_ZEROES:
969 		flags = 0;
970 		break;
971 	default:
972 		error = -EOPNOTSUPP;
973 		goto fail;
974 	}
975 
976 	/*
977 	 * Invalidate the page cache, including dirty pages, for valid
978 	 * de-allocate mode calls to fallocate().
979 	 */
980 	error = truncate_bdev_range(bdev, file_to_blk_mode(file), start, end);
981 	if (error)
982 		goto fail;
983 
984 	error = blkdev_issue_zeroout(bdev, start >> SECTOR_SHIFT,
985 				     len >> SECTOR_SHIFT, GFP_KERNEL, flags);
986  fail:
987 	filemap_invalidate_unlock(inode->i_mapping);
988 	inode_unlock(inode);
989 	return error;
990 }
991 
992 static int blkdev_mmap_prepare(struct vm_area_desc *desc)
993 {
994 	struct file *file = desc->file;
995 
996 	if (bdev_read_only(I_BDEV(bdev_file_inode(file))))
997 		return generic_file_readonly_mmap_prepare(desc);
998 
999 	return generic_file_mmap_prepare(desc);
1000 }
1001 
1002 const struct file_operations def_blk_fops = {
1003 	.open		= blkdev_open,
1004 	.release	= blkdev_release,
1005 	.llseek		= blkdev_llseek,
1006 	.read_iter	= blkdev_read_iter,
1007 	.write_iter	= blkdev_write_iter,
1008 	.iopoll		= iocb_bio_iopoll,
1009 	.mmap_prepare	= blkdev_mmap_prepare,
1010 	.fsync		= blkdev_fsync,
1011 	.unlocked_ioctl	= blkdev_ioctl,
1012 #ifdef CONFIG_COMPAT
1013 	.compat_ioctl	= compat_blkdev_ioctl,
1014 #endif
1015 	.splice_read	= blkdev_splice_read,
1016 	.splice_write	= iter_file_splice_write,
1017 	.fallocate	= blkdev_fallocate,
1018 	.uring_cmd	= blkdev_uring_cmd,
1019 	.fop_flags	= FOP_BUFFER_RASYNC | FOP_DONTCACHE,
1020 };
1021 
1022 static __init int blkdev_init(void)
1023 {
1024 	return bioset_init(&blkdev_dio_pool, 4,
1025 				offsetof(struct blkdev_dio, bio),
1026 				BIOSET_NEED_BVECS|BIOSET_PERCPU_CACHE);
1027 }
1028 module_init(blkdev_init);
1029