xref: /openbmc/linux/fs/direct-io.c (revision d44c4042)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  * fs/direct-io.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  * Copyright (C) 2002, Linus Torvalds.
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  * O_DIRECT
81da177e4SLinus Torvalds  *
9e1f8e874SFrancois Cami  * 04Jul2002	Andrew Morton
101da177e4SLinus Torvalds  *		Initial version
111da177e4SLinus Torvalds  * 11Sep2002	janetinc@us.ibm.com
121da177e4SLinus Torvalds  * 		added readv/writev support.
13e1f8e874SFrancois Cami  * 29Oct2002	Andrew Morton
141da177e4SLinus Torvalds  *		rewrote bio_add_page() support.
151da177e4SLinus Torvalds  * 30Oct2002	pbadari@us.ibm.com
161da177e4SLinus Torvalds  *		added support for non-aligned IO.
171da177e4SLinus Torvalds  * 06Nov2002	pbadari@us.ibm.com
181da177e4SLinus Torvalds  *		added asynchronous IO support.
191da177e4SLinus Torvalds  * 21Jul2003	nathans@sgi.com
201da177e4SLinus Torvalds  *		added IO completion notifier.
211da177e4SLinus Torvalds  */
221da177e4SLinus Torvalds 
231da177e4SLinus Torvalds #include <linux/kernel.h>
241da177e4SLinus Torvalds #include <linux/module.h>
251da177e4SLinus Torvalds #include <linux/types.h>
261da177e4SLinus Torvalds #include <linux/fs.h>
271da177e4SLinus Torvalds #include <linux/mm.h>
281da177e4SLinus Torvalds #include <linux/slab.h>
291da177e4SLinus Torvalds #include <linux/highmem.h>
301da177e4SLinus Torvalds #include <linux/pagemap.h>
3198c4d57dSAndrew Morton #include <linux/task_io_accounting_ops.h>
321da177e4SLinus Torvalds #include <linux/bio.h>
331da177e4SLinus Torvalds #include <linux/wait.h>
341da177e4SLinus Torvalds #include <linux/err.h>
351da177e4SLinus Torvalds #include <linux/blkdev.h>
361da177e4SLinus Torvalds #include <linux/buffer_head.h>
371da177e4SLinus Torvalds #include <linux/rwsem.h>
381da177e4SLinus Torvalds #include <linux/uio.h>
3960063497SArun Sharma #include <linux/atomic.h>
4065dd2aa9SAndi Kleen #include <linux/prefetch.h>
411da177e4SLinus Torvalds 
42b16155a0SEric Biggers #include "internal.h"
43b16155a0SEric Biggers 
441da177e4SLinus Torvalds /*
451ccf164eSDavid Howells  * How many user pages to map in one call to iov_iter_extract_pages().  This
461ccf164eSDavid Howells  * determines the size of a structure in the slab cache
471da177e4SLinus Torvalds  */
481da177e4SLinus Torvalds #define DIO_PAGES	64
491da177e4SLinus Torvalds 
501da177e4SLinus Torvalds /*
51ffe51f01SLukas Czerner  * Flags for dio_complete()
52ffe51f01SLukas Czerner  */
53ffe51f01SLukas Czerner #define DIO_COMPLETE_ASYNC		0x01	/* This is async IO */
54ffe51f01SLukas Czerner #define DIO_COMPLETE_INVALIDATE		0x02	/* Can invalidate pages */
55ffe51f01SLukas Czerner 
56ffe51f01SLukas Czerner /*
571da177e4SLinus Torvalds  * This code generally works in units of "dio_blocks".  A dio_block is
581da177e4SLinus Torvalds  * somewhere between the hard sector size and the filesystem block size.  it
591da177e4SLinus Torvalds  * is determined on a per-invocation basis.   When talking to the filesystem
601da177e4SLinus Torvalds  * we need to convert dio_blocks to fs_blocks by scaling the dio_block quantity
611da177e4SLinus Torvalds  * down by dio->blkfactor.  Similarly, fs-blocksize quantities are converted
621da177e4SLinus Torvalds  * to bio_block quantities by shifting left by blkfactor.
631da177e4SLinus Torvalds  *
641da177e4SLinus Torvalds  * If blkfactor is zero then the user's request was aligned to the filesystem's
651da177e4SLinus Torvalds  * blocksize.
661da177e4SLinus Torvalds  */
671da177e4SLinus Torvalds 
68eb28be2bSAndi Kleen /* dio_state only used in the submission path */
69eb28be2bSAndi Kleen 
70eb28be2bSAndi Kleen struct dio_submit {
711da177e4SLinus Torvalds 	struct bio *bio;		/* bio under assembly */
721da177e4SLinus Torvalds 	unsigned blkbits;		/* doesn't change */
731da177e4SLinus Torvalds 	unsigned blkfactor;		/* When we're using an alignment which
741da177e4SLinus Torvalds 					   is finer than the filesystem's soft
751da177e4SLinus Torvalds 					   blocksize, this specifies how much
761da177e4SLinus Torvalds 					   finer.  blkfactor=2 means 1/4-block
771da177e4SLinus Torvalds 					   alignment.  Does not change */
781da177e4SLinus Torvalds 	unsigned start_zero_done;	/* flag: sub-blocksize zeroing has
791da177e4SLinus Torvalds 					   been performed at the start of a
801da177e4SLinus Torvalds 					   write */
811da177e4SLinus Torvalds 	int pages_in_io;		/* approximate total IO pages */
821da177e4SLinus Torvalds 	sector_t block_in_file;		/* Current offset into the underlying
831da177e4SLinus Torvalds 					   file in dio_block units. */
841da177e4SLinus Torvalds 	unsigned blocks_available;	/* At block_in_file.  changes */
850dc2bc49SAndi Kleen 	int reap_counter;		/* rate limit reaping */
861da177e4SLinus Torvalds 	sector_t final_block_in_request;/* doesn't change */
871da177e4SLinus Torvalds 	int boundary;			/* prev block is at a boundary */
881d8fa7a2SBadari Pulavarty 	get_block_t *get_block;		/* block mapping function */
89eb28be2bSAndi Kleen 
90facd07b0SJosef Bacik 	loff_t logical_offset_in_bio;	/* current first logical block in bio */
911da177e4SLinus Torvalds 	sector_t final_block_in_bio;	/* current final block in bio + 1 */
921da177e4SLinus Torvalds 	sector_t next_block_for_io;	/* next block to be put under IO,
931da177e4SLinus Torvalds 					   in dio_blocks units */
941da177e4SLinus Torvalds 
951da177e4SLinus Torvalds 	/*
961da177e4SLinus Torvalds 	 * Deferred addition of a page to the dio.  These variables are
971da177e4SLinus Torvalds 	 * private to dio_send_cur_page(), submit_page_section() and
981da177e4SLinus Torvalds 	 * dio_bio_add_page().
991da177e4SLinus Torvalds 	 */
1001da177e4SLinus Torvalds 	struct page *cur_page;		/* The page */
1011da177e4SLinus Torvalds 	unsigned cur_page_offset;	/* Offset into it, in bytes */
1021da177e4SLinus Torvalds 	unsigned cur_page_len;		/* Nr of bytes at cur_page_offset */
1031da177e4SLinus Torvalds 	sector_t cur_page_block;	/* Where it starts */
104facd07b0SJosef Bacik 	loff_t cur_page_fs_offset;	/* Offset in file */
1051da177e4SLinus Torvalds 
1067b2c99d1SAl Viro 	struct iov_iter *iter;
10723aee091SJeff Moyer 	/*
10823aee091SJeff Moyer 	 * Page queue.  These variables belong to dio_refill_pages() and
10923aee091SJeff Moyer 	 * dio_get_page().
11023aee091SJeff Moyer 	 */
11123aee091SJeff Moyer 	unsigned head;			/* next page to process */
11223aee091SJeff Moyer 	unsigned tail;			/* last valid page + 1 */
1137b2c99d1SAl Viro 	size_t from, to;
114eb28be2bSAndi Kleen };
115eb28be2bSAndi Kleen 
116eb28be2bSAndi Kleen /* dio_state communicated between submission path and end_io */
117eb28be2bSAndi Kleen struct dio {
118eb28be2bSAndi Kleen 	int flags;			/* doesn't change */
119c6293eacSBart Van Assche 	blk_opf_t opf;			/* request operation type and flags */
12074d46992SChristoph Hellwig 	struct gendisk *bio_disk;
1210dc2bc49SAndi Kleen 	struct inode *inode;
122eb28be2bSAndi Kleen 	loff_t i_size;			/* i_size when submitted */
123eb28be2bSAndi Kleen 	dio_iodone_t *end_io;		/* IO completion function */
1241ccf164eSDavid Howells 	bool is_pinned;			/* T if we have pins on the pages */
125eb28be2bSAndi Kleen 
12618772641SAndi Kleen 	void *private;			/* copy from map_bh.b_private */
127eb28be2bSAndi Kleen 
128eb28be2bSAndi Kleen 	/* BIO completion state */
129eb28be2bSAndi Kleen 	spinlock_t bio_lock;		/* protects BIO fields below */
1301ccf164eSDavid Howells 	int page_errors;		/* err from iov_iter_extract_pages() */
1310dc2bc49SAndi Kleen 	int is_async;			/* is IO async ? */
1327b7a8665SChristoph Hellwig 	bool defer_completion;		/* defer AIO completion to workqueue? */
13353cbf3b1SMing Lei 	bool should_dirty;		/* if pages should be dirtied */
1340dc2bc49SAndi Kleen 	int io_error;			/* IO error in completion path */
135eb28be2bSAndi Kleen 	unsigned long refcount;		/* direct_io_worker() and bios */
136eb28be2bSAndi Kleen 	struct bio *bio_list;		/* singly linked via bi_private */
137eb28be2bSAndi Kleen 	struct task_struct *waiter;	/* waiting task (NULL if none) */
138eb28be2bSAndi Kleen 
139eb28be2bSAndi Kleen 	/* AIO related stuff */
140eb28be2bSAndi Kleen 	struct kiocb *iocb;		/* kiocb */
141eb28be2bSAndi Kleen 	ssize_t result;                 /* IO result */
142eb28be2bSAndi Kleen 
14323aee091SJeff Moyer 	/*
14423aee091SJeff Moyer 	 * pages[] (and any fields placed after it) are not zeroed out at
14523aee091SJeff Moyer 	 * allocation time.  Don't add new fields after pages[] unless you
14623aee091SJeff Moyer 	 * wish that they not be zeroed.
14723aee091SJeff Moyer 	 */
1487b7a8665SChristoph Hellwig 	union {
14923aee091SJeff Moyer 		struct page *pages[DIO_PAGES];	/* page buffer */
1507b7a8665SChristoph Hellwig 		struct work_struct complete_work;/* deferred AIO completion */
1517b7a8665SChristoph Hellwig 	};
1526e8267f5SAndi Kleen } ____cacheline_aligned_in_smp;
1536e8267f5SAndi Kleen 
1546e8267f5SAndi Kleen static struct kmem_cache *dio_cache __read_mostly;
1551da177e4SLinus Torvalds 
1561da177e4SLinus Torvalds /*
1571da177e4SLinus Torvalds  * How many pages are in the queue?
1581da177e4SLinus Torvalds  */
dio_pages_present(struct dio_submit * sdio)159eb28be2bSAndi Kleen static inline unsigned dio_pages_present(struct dio_submit *sdio)
1601da177e4SLinus Torvalds {
161eb28be2bSAndi Kleen 	return sdio->tail - sdio->head;
1621da177e4SLinus Torvalds }
1631da177e4SLinus Torvalds 
1641da177e4SLinus Torvalds /*
1651da177e4SLinus Torvalds  * Go grab and pin some userspace pages.   Typically we'll get 64 at a time.
1661da177e4SLinus Torvalds  */
dio_refill_pages(struct dio * dio,struct dio_submit * sdio)167ba253fbfSAndi Kleen static inline int dio_refill_pages(struct dio *dio, struct dio_submit *sdio)
1681da177e4SLinus Torvalds {
1691ccf164eSDavid Howells 	struct page **pages = dio->pages;
170c6293eacSBart Van Assche 	const enum req_op dio_op = dio->opf & REQ_OP_MASK;
1717b2c99d1SAl Viro 	ssize_t ret;
1721da177e4SLinus Torvalds 
1731ccf164eSDavid Howells 	ret = iov_iter_extract_pages(sdio->iter, &pages, LONG_MAX,
1741ccf164eSDavid Howells 				     DIO_PAGES, 0, &sdio->from);
1751da177e4SLinus Torvalds 
176c6293eacSBart Van Assche 	if (ret < 0 && sdio->blocks_available && dio_op == REQ_OP_WRITE) {
1771da177e4SLinus Torvalds 		/*
1781da177e4SLinus Torvalds 		 * A memory fault, but the filesystem has some outstanding
1791da177e4SLinus Torvalds 		 * mapped blocks.  We need to use those blocks up to avoid
1801da177e4SLinus Torvalds 		 * leaking stale data in the file.
1811da177e4SLinus Torvalds 		 */
1821da177e4SLinus Torvalds 		if (dio->page_errors == 0)
1831da177e4SLinus Torvalds 			dio->page_errors = ret;
1841ccf164eSDavid Howells 		dio->pages[0] = ZERO_PAGE(0);
185eb28be2bSAndi Kleen 		sdio->head = 0;
186eb28be2bSAndi Kleen 		sdio->tail = 1;
1877b2c99d1SAl Viro 		sdio->from = 0;
1887b2c99d1SAl Viro 		sdio->to = PAGE_SIZE;
1897b2c99d1SAl Viro 		return 0;
1901da177e4SLinus Torvalds 	}
1911da177e4SLinus Torvalds 
1921da177e4SLinus Torvalds 	if (ret >= 0) {
1937b2c99d1SAl Viro 		ret += sdio->from;
194eb28be2bSAndi Kleen 		sdio->head = 0;
1957b2c99d1SAl Viro 		sdio->tail = (ret + PAGE_SIZE - 1) / PAGE_SIZE;
1967b2c99d1SAl Viro 		sdio->to = ((ret - 1) & (PAGE_SIZE - 1)) + 1;
1977b2c99d1SAl Viro 		return 0;
1981da177e4SLinus Torvalds 	}
1991da177e4SLinus Torvalds 	return ret;
2001da177e4SLinus Torvalds }
2011da177e4SLinus Torvalds 
2021da177e4SLinus Torvalds /*
2031da177e4SLinus Torvalds  * Get another userspace page.  Returns an ERR_PTR on error.  Pages are
2041ccf164eSDavid Howells  * buffered inside the dio so that we can call iov_iter_extract_pages()
2051ccf164eSDavid Howells  * against a decent number of pages, less frequently.  To provide nicer use of
2061ccf164eSDavid Howells  * the L1 cache.
2071da177e4SLinus Torvalds  */
dio_get_page(struct dio * dio,struct dio_submit * sdio)208ba253fbfSAndi Kleen static inline struct page *dio_get_page(struct dio *dio,
2096fcc5420SBoaz Harrosh 					struct dio_submit *sdio)
2101da177e4SLinus Torvalds {
211eb28be2bSAndi Kleen 	if (dio_pages_present(sdio) == 0) {
2121da177e4SLinus Torvalds 		int ret;
2131da177e4SLinus Torvalds 
214eb28be2bSAndi Kleen 		ret = dio_refill_pages(dio, sdio);
2151da177e4SLinus Torvalds 		if (ret)
2161da177e4SLinus Torvalds 			return ERR_PTR(ret);
217eb28be2bSAndi Kleen 		BUG_ON(dio_pages_present(sdio) == 0);
2181da177e4SLinus Torvalds 	}
2196fcc5420SBoaz Harrosh 	return dio->pages[sdio->head];
2201da177e4SLinus Torvalds }
2211da177e4SLinus Torvalds 
dio_pin_page(struct dio * dio,struct page * page)2221ccf164eSDavid Howells static void dio_pin_page(struct dio *dio, struct page *page)
2231ccf164eSDavid Howells {
2241ccf164eSDavid Howells 	if (dio->is_pinned)
2251ccf164eSDavid Howells 		folio_add_pin(page_folio(page));
2261ccf164eSDavid Howells }
2271ccf164eSDavid Howells 
dio_unpin_page(struct dio * dio,struct page * page)2281ccf164eSDavid Howells static void dio_unpin_page(struct dio *dio, struct page *page)
2291ccf164eSDavid Howells {
2301ccf164eSDavid Howells 	if (dio->is_pinned)
2311ccf164eSDavid Howells 		unpin_user_page(page);
2321ccf164eSDavid Howells }
2331ccf164eSDavid Howells 
2345a9d929dSDarrick J. Wong /*
2356d544bb4SZach Brown  * dio_complete() - called when all DIO BIO I/O has been completed
2366d544bb4SZach Brown  *
2377b7a8665SChristoph Hellwig  * This drops i_dio_count, lets interested parties know that a DIO operation
2387b7a8665SChristoph Hellwig  * has completed, and calculates the resulting return code for the operation.
2396d544bb4SZach Brown  *
2406d544bb4SZach Brown  * It lets the filesystem know if it registered an interest earlier via
2416d544bb4SZach Brown  * get_block.  Pass the private field of the map buffer_head so that
2426d544bb4SZach Brown  * filesystems can use it to hold additional state between get_block calls and
2436d544bb4SZach Brown  * dio_complete.
2441da177e4SLinus Torvalds  */
dio_complete(struct dio * dio,ssize_t ret,unsigned int flags)245ffe51f01SLukas Czerner static ssize_t dio_complete(struct dio *dio, ssize_t ret, unsigned int flags)
2461da177e4SLinus Torvalds {
247c6293eacSBart Van Assche 	const enum req_op dio_op = dio->opf & REQ_OP_MASK;
248716b9bc0SChristoph Hellwig 	loff_t offset = dio->iocb->ki_pos;
2496d544bb4SZach Brown 	ssize_t transferred = 0;
250332391a9SLukas Czerner 	int err;
2516d544bb4SZach Brown 
2528459d86aSZach Brown 	/*
2538459d86aSZach Brown 	 * AIO submission can race with bio completion to get here while
2548459d86aSZach Brown 	 * expecting to have the last io completed by bio completion.
2558459d86aSZach Brown 	 * In that case -EIOCBQUEUED is in fact not an error we want
2568459d86aSZach Brown 	 * to preserve through this call.
2578459d86aSZach Brown 	 */
2588459d86aSZach Brown 	if (ret == -EIOCBQUEUED)
2598459d86aSZach Brown 		ret = 0;
2608459d86aSZach Brown 
2616d544bb4SZach Brown 	if (dio->result) {
2626d544bb4SZach Brown 		transferred = dio->result;
2636d544bb4SZach Brown 
2646d544bb4SZach Brown 		/* Check for short read case */
265c6293eacSBart Van Assche 		if (dio_op == REQ_OP_READ &&
2668a4c1e42SMike Christie 		    ((offset + transferred) > dio->i_size))
2676d544bb4SZach Brown 			transferred = dio->i_size - offset;
2684038acdbSAl Viro 		/* ignore EFAULT if some IO has been done */
2694038acdbSAl Viro 		if (unlikely(ret == -EFAULT) && transferred)
2704038acdbSAl Viro 			ret = 0;
2716d544bb4SZach Brown 	}
2726d544bb4SZach Brown 
2736d544bb4SZach Brown 	if (ret == 0)
2746d544bb4SZach Brown 		ret = dio->page_errors;
2756d544bb4SZach Brown 	if (ret == 0)
2766d544bb4SZach Brown 		ret = dio->io_error;
2776d544bb4SZach Brown 	if (ret == 0)
2786d544bb4SZach Brown 		ret = transferred;
2796d544bb4SZach Brown 
2805e25c269SEryu Guan 	if (dio->end_io) {
2815e25c269SEryu Guan 		// XXX: ki_pos??
2825e25c269SEryu Guan 		err = dio->end_io(dio->iocb, offset, ret, dio->private);
2835e25c269SEryu Guan 		if (err)
2845e25c269SEryu Guan 			ret = err;
2855e25c269SEryu Guan 	}
2865e25c269SEryu Guan 
287332391a9SLukas Czerner 	/*
288332391a9SLukas Czerner 	 * Try again to invalidate clean pages which might have been cached by
289332391a9SLukas Czerner 	 * non-direct readahead, or faulted in by get_user_pages() if the source
290332391a9SLukas Czerner 	 * of the write was an mmap'ed region of the file we're writing.  Either
291332391a9SLukas Czerner 	 * one is a pretty crazy thing to do, so we don't support it 100%.  If
292332391a9SLukas Czerner 	 * this invalidation fails, tough, the write still worked...
2935e25c269SEryu Guan 	 *
2945e25c269SEryu Guan 	 * And this page cache invalidation has to be after dio->end_io(), as
2955e25c269SEryu Guan 	 * some filesystems convert unwritten extents to real allocations in
2965e25c269SEryu Guan 	 * end_io() when necessary, otherwise a racing buffer read would cache
2975e25c269SEryu Guan 	 * zeros from unwritten extents.
298332391a9SLukas Czerner 	 */
299ffe51f01SLukas Czerner 	if (flags & DIO_COMPLETE_INVALIDATE &&
300c6293eacSBart Van Assche 	    ret > 0 && dio_op == REQ_OP_WRITE)
301332391a9SLukas Czerner 		kiocb_invalidate_post_direct_write(dio->iocb, ret);
302332391a9SLukas Czerner 
303332391a9SLukas Czerner 	inode_dio_end(dio->inode);
304332391a9SLukas Czerner 
3055a9d929dSDarrick J. Wong 	if (flags & DIO_COMPLETE_ASYNC) {
3065a9d929dSDarrick J. Wong 		/*
307332391a9SLukas Czerner 		 * generic_write_sync expects ki_pos to have been updated
308332391a9SLukas Czerner 		 * already, but the submission path only does this for
309fe0f07d0SJens Axboe 		 * synchronous I/O.
310fe0f07d0SJens Axboe 		 */
311ffe51f01SLukas Czerner 		dio->iocb->ki_pos += transferred;
312e2592217SChristoph Hellwig 
313e2592217SChristoph Hellwig 		if (ret > 0 && dio_op == REQ_OP_WRITE)
314e2592217SChristoph Hellwig 			ret = generic_write_sync(dio->iocb, ret);
315e2592217SChristoph Hellwig 		dio->iocb->ki_complete(dio->iocb, ret);
316e2592217SChristoph Hellwig 	}
317e2592217SChristoph Hellwig 
31802afc27fSChristoph Hellwig 	kmem_cache_free(dio_cache, dio);
319c6293eacSBart Van Assche 	return ret;
32041e817bcSMaximilian Heyne }
3216b19b766SJens Axboe 
dio_aio_complete_work(struct work_struct * work)32202afc27fSChristoph Hellwig static void dio_aio_complete_work(struct work_struct *work)
32340e2e973SChristoph Hellwig {
3247b7a8665SChristoph Hellwig 	struct dio *dio = container_of(work, struct dio, complete_work);
3256d544bb4SZach Brown 
3261da177e4SLinus Torvalds 	dio_complete(dio, 0, DIO_COMPLETE_ASYNC | DIO_COMPLETE_INVALIDATE);
3271da177e4SLinus Torvalds }
3287b7a8665SChristoph Hellwig 
3297b7a8665SChristoph Hellwig static blk_status_t dio_bio_complete(struct dio *dio, struct bio *bio);
3307b7a8665SChristoph Hellwig 
3317b7a8665SChristoph Hellwig /*
332ffe51f01SLukas Czerner  * Asynchronous IO callback.
3337b7a8665SChristoph Hellwig  */
dio_bio_end_aio(struct bio * bio)3347b7a8665SChristoph Hellwig static void dio_bio_end_aio(struct bio *bio)
3354e4cbee9SChristoph Hellwig {
3367b7a8665SChristoph Hellwig 	struct dio *dio = bio->bi_private;
3371da177e4SLinus Torvalds 	const enum req_op dio_op = dio->opf & REQ_OP_MASK;
3381da177e4SLinus Torvalds 	unsigned long remaining;
3391da177e4SLinus Torvalds 	unsigned long flags;
3404246a0b6SChristoph Hellwig 	bool defer_completion = false;
3411da177e4SLinus Torvalds 
3421da177e4SLinus Torvalds 	/* cleanup the bio */
343c6293eacSBart Van Assche 	dio_bio_complete(dio, bio);
3445eb6c7a2SZach Brown 
3455eb6c7a2SZach Brown 	spin_lock_irqsave(&dio->bio_lock, flags);
346332391a9SLukas Czerner 	remaining = --dio->refcount;
3471da177e4SLinus Torvalds 	if (remaining == 1 && dio->waiter)
3481da177e4SLinus Torvalds 		wake_up_process(dio->waiter);
3491da177e4SLinus Torvalds 	spin_unlock_irqrestore(&dio->bio_lock, flags);
3500273201eSZach Brown 
3515eb6c7a2SZach Brown 	if (remaining == 0) {
3525eb6c7a2SZach Brown 		/*
3535eb6c7a2SZach Brown 		 * Defer completion when defer_completion is set or
35420258b2bSZach Brown 		 * when the inode has pages mapped and this is AIO write.
3555eb6c7a2SZach Brown 		 * We need to invalidate those pages because there is a
35620258b2bSZach Brown 		 * chance they contain stale data in the case buffered IO
3578459d86aSZach Brown 		 * went in between AIO submission and completion into the
358332391a9SLukas Czerner 		 * same region.
359332391a9SLukas Czerner 		 */
360332391a9SLukas Czerner 		if (dio->result)
361332391a9SLukas Czerner 			defer_completion = dio->defer_completion ||
362332391a9SLukas Czerner 					   (dio_op == REQ_OP_WRITE &&
363332391a9SLukas Czerner 					    dio->inode->i_mapping->nrpages);
364332391a9SLukas Czerner 		if (defer_completion) {
365332391a9SLukas Czerner 			INIT_WORK(&dio->complete_work, dio_aio_complete_work);
366332391a9SLukas Czerner 			queue_work(dio->inode->i_sb->s_dio_done_wq,
367332391a9SLukas Czerner 				   &dio->complete_work);
368c6293eacSBart Van Assche 		} else {
369332391a9SLukas Czerner 			dio_complete(dio, 0, DIO_COMPLETE_ASYNC);
370332391a9SLukas Czerner 		}
3717b7a8665SChristoph Hellwig 	}
3727b7a8665SChristoph Hellwig }
3737b7a8665SChristoph Hellwig 
3747b7a8665SChristoph Hellwig /*
375ffe51f01SLukas Czerner  * The BIO completion handler simply queues the BIO up for the process-context
3767b7a8665SChristoph Hellwig  * handler.
3778459d86aSZach Brown  *
3781da177e4SLinus Torvalds  * During I/O bi_private points at the dio.  After I/O, bi_private is used to
3791da177e4SLinus Torvalds  * implement a singly-linked list of completed BIOs, at dio->bio_list.
3801da177e4SLinus Torvalds  */
dio_bio_end_io(struct bio * bio)3811da177e4SLinus Torvalds static void dio_bio_end_io(struct bio *bio)
3821da177e4SLinus Torvalds {
3831da177e4SLinus Torvalds 	struct dio *dio = bio->bi_private;
3841da177e4SLinus Torvalds 	unsigned long flags;
3851da177e4SLinus Torvalds 
3861da177e4SLinus Torvalds 	spin_lock_irqsave(&dio->bio_lock, flags);
3874246a0b6SChristoph Hellwig 	bio->bi_private = dio->bio_list;
3881da177e4SLinus Torvalds 	dio->bio_list = bio;
3891da177e4SLinus Torvalds 	if (--dio->refcount == 1 && dio->waiter)
3901da177e4SLinus Torvalds 		wake_up_process(dio->waiter);
3911da177e4SLinus Torvalds 	spin_unlock_irqrestore(&dio->bio_lock, flags);
3921da177e4SLinus Torvalds }
3931da177e4SLinus Torvalds 
3941da177e4SLinus Torvalds static inline void
dio_bio_alloc(struct dio * dio,struct dio_submit * sdio,struct block_device * bdev,sector_t first_sector,int nr_vecs)3955eb6c7a2SZach Brown dio_bio_alloc(struct dio *dio, struct dio_submit *sdio,
3961da177e4SLinus Torvalds 	      struct block_device *bdev,
3971da177e4SLinus Torvalds 	      sector_t first_sector, int nr_vecs)
3981da177e4SLinus Torvalds {
3991da177e4SLinus Torvalds 	struct bio *bio;
400ba253fbfSAndi Kleen 
401eb28be2bSAndi Kleen 	/*
402eb28be2bSAndi Kleen 	 * bio_alloc() is guaranteed to return a bio when allowed to sleep and
4031da177e4SLinus Torvalds 	 * we request a valid number of vectors.
4041da177e4SLinus Torvalds 	 */
4051da177e4SLinus Torvalds 	bio = bio_alloc(bdev, nr_vecs, dio->opf, GFP_KERNEL);
4061da177e4SLinus Torvalds 	bio->bi_iter.bi_sector = first_sector;
40720d9600cSDavid Dillow 	if (dio->is_async)
4080eb0b63cSChristoph Hellwig 		bio->bi_end_io = dio_bio_end_aio;
4090eb0b63cSChristoph Hellwig 	else
41020d9600cSDavid Dillow 		bio->bi_end_io = dio_bio_end_io;
411c6293eacSBart Van Assche 	if (dio->is_pinned)
4124f024f37SKent Overstreet 		bio_set_flag(bio, BIO_PAGE_PINNED);
4131da177e4SLinus Torvalds 	sdio->bio = bio;
4141da177e4SLinus Torvalds 	sdio->logical_offset_in_bio = sdio->cur_page_fs_offset;
4151da177e4SLinus Torvalds }
4161da177e4SLinus Torvalds 
4171ccf164eSDavid Howells /*
4181ccf164eSDavid Howells  * In the AIO read case we speculatively dirty the pages before starting IO.
419eb28be2bSAndi Kleen  * During IO completion, any of these pages which happen to have been written
420eb28be2bSAndi Kleen  * back will be redirtied by bio_check_pages_dirty().
4211da177e4SLinus Torvalds  *
4221da177e4SLinus Torvalds  * bios hold a dio reference between submit_bio and ->end_io.
4231da177e4SLinus Torvalds  */
dio_bio_submit(struct dio * dio,struct dio_submit * sdio)4241da177e4SLinus Torvalds static inline void dio_bio_submit(struct dio *dio, struct dio_submit *sdio)
4251da177e4SLinus Torvalds {
4261da177e4SLinus Torvalds 	const enum req_op dio_op = dio->opf & REQ_OP_MASK;
4270273201eSZach Brown 	struct bio *bio = sdio->bio;
4280273201eSZach Brown 	unsigned long flags;
4291da177e4SLinus Torvalds 
430ba253fbfSAndi Kleen 	bio->bi_private = dio;
4311da177e4SLinus Torvalds 
432c6293eacSBart Van Assche 	spin_lock_irqsave(&dio->bio_lock, flags);
433eb28be2bSAndi Kleen 	dio->refcount++;
4345eb6c7a2SZach Brown 	spin_unlock_irqrestore(&dio->bio_lock, flags);
4351da177e4SLinus Torvalds 
4361da177e4SLinus Torvalds 	if (dio->is_async && dio_op == REQ_OP_READ && dio->should_dirty)
4375eb6c7a2SZach Brown 		bio_set_pages_dirty(bio);
4385eb6c7a2SZach Brown 
4395eb6c7a2SZach Brown 	dio->bio_disk = bio->bi_bdev->bd_disk;
4405eb6c7a2SZach Brown 
4415eb6c7a2SZach Brown 	submit_bio(bio);
442c6293eacSBart Van Assche 
4431da177e4SLinus Torvalds 	sdio->bio = NULL;
4445eb6c7a2SZach Brown 	sdio->boundary = 0;
445309dca30SChristoph Hellwig 	sdio->logical_offset_in_bio = 0;
446c1c53460SJens Axboe }
44794c2ed58SChristoph Hellwig 
4481da177e4SLinus Torvalds /*
449eb28be2bSAndi Kleen  * Release any resources in case of a failure
450eb28be2bSAndi Kleen  */
dio_cleanup(struct dio * dio,struct dio_submit * sdio)451eb28be2bSAndi Kleen static inline void dio_cleanup(struct dio *dio, struct dio_submit *sdio)
4521da177e4SLinus Torvalds {
4531da177e4SLinus Torvalds 	if (dio->is_pinned)
4541da177e4SLinus Torvalds 		unpin_user_pages(dio->pages + sdio->head,
4551da177e4SLinus Torvalds 				 sdio->tail - sdio->head);
4561da177e4SLinus Torvalds 	sdio->head = sdio->tail;
457ba253fbfSAndi Kleen }
4581da177e4SLinus Torvalds 
4591ccf164eSDavid Howells /*
4601ccf164eSDavid Howells  * Wait for the next BIO to complete.  Remove it and return it.  NULL is
4611ccf164eSDavid Howells  * returned once all BIOs have been completed.  This must only be called once
462*d44c4042SDavid Howells  * all bios have been issued so that dio->refcount can only decrease.  This
4631da177e4SLinus Torvalds  * requires that the caller hold a reference on the dio.
4641da177e4SLinus Torvalds  */
dio_await_one(struct dio * dio)4651da177e4SLinus Torvalds static struct bio *dio_await_one(struct dio *dio)
4660273201eSZach Brown {
4670273201eSZach Brown 	unsigned long flags;
4680273201eSZach Brown 	struct bio *bio = NULL;
4693d742d4bSRandy Dunlap 
4701da177e4SLinus Torvalds 	spin_lock_irqsave(&dio->bio_lock, flags);
4711da177e4SLinus Torvalds 
4721da177e4SLinus Torvalds 	/*
4731da177e4SLinus Torvalds 	 * Wait as long as the list is empty and there are bios in flight.  bio
4740273201eSZach Brown 	 * completion drops the count, maybe adds to the list, and wakes while
4751da177e4SLinus Torvalds 	 * holding the bio_lock so we don't need set_current_state()'s barrier
4761da177e4SLinus Torvalds 	 * and can call it after testing our condition.
4775eb6c7a2SZach Brown 	 */
4785eb6c7a2SZach Brown 	while (dio->refcount > 1 && dio->bio_list == NULL) {
4795eb6c7a2SZach Brown 		__set_current_state(TASK_UNINTERRUPTIBLE);
4805eb6c7a2SZach Brown 		dio->waiter = current;
4815eb6c7a2SZach Brown 		spin_unlock_irqrestore(&dio->bio_lock, flags);
4825eb6c7a2SZach Brown 		blk_io_schedule();
4835eb6c7a2SZach Brown 		/* wake up sets us TASK_RUNNING */
4845eb6c7a2SZach Brown 		spin_lock_irqsave(&dio->bio_lock, flags);
4855eb6c7a2SZach Brown 		dio->waiter = NULL;
4861da177e4SLinus Torvalds 	}
4871da177e4SLinus Torvalds 	if (dio->bio_list) {
488e6249cddSMing Lei 		bio = dio->bio_list;
4895eb6c7a2SZach Brown 		dio->bio_list = bio->bi_private;
4901da177e4SLinus Torvalds 	}
4911da177e4SLinus Torvalds 	spin_unlock_irqrestore(&dio->bio_lock, flags);
4921da177e4SLinus Torvalds 	return bio;
4930273201eSZach Brown }
4941da177e4SLinus Torvalds 
4951da177e4SLinus Torvalds /*
4960273201eSZach Brown  * Process one completed BIO.  No locks are held.
4971da177e4SLinus Torvalds  */
dio_bio_complete(struct dio * dio,struct bio * bio)4981da177e4SLinus Torvalds static blk_status_t dio_bio_complete(struct dio *dio, struct bio *bio)
4991da177e4SLinus Torvalds {
5001da177e4SLinus Torvalds 	blk_status_t err = bio->bi_status;
5011da177e4SLinus Torvalds 	const enum req_op dio_op = dio->opf & REQ_OP_MASK;
5021da177e4SLinus Torvalds 	bool should_dirty = dio_op == REQ_OP_READ && dio->should_dirty;
5031da177e4SLinus Torvalds 
5044e4cbee9SChristoph Hellwig 	if (err) {
5051da177e4SLinus Torvalds 		if (err == BLK_STS_AGAIN && (bio->bi_opf & REQ_NOWAIT))
5064e4cbee9SChristoph Hellwig 			dio->io_error = -EAGAIN;
507c6293eacSBart Van Assche 		else
508c6293eacSBart Van Assche 			dio->io_error = -EIO;
5091da177e4SLinus Torvalds 	}
51003a07c92SGoldwyn Rodrigues 
51103a07c92SGoldwyn Rodrigues 	if (dio->is_async && should_dirty) {
51203a07c92SGoldwyn Rodrigues 		bio_check_pages_dirty(bio);	/* transfers ownership */
51303a07c92SGoldwyn Rodrigues 	} else {
514174e27c6SChen, Kenneth W 		bio_release_pages(bio, should_dirty);
51503a07c92SGoldwyn Rodrigues 		bio_put(bio);
5161da177e4SLinus Torvalds 	}
517d7c8aa85SChristoph Hellwig 	return err;
5187ddc971fSMike Krinkin }
5191da177e4SLinus Torvalds 
520d7c8aa85SChristoph Hellwig /*
5211da177e4SLinus Torvalds  * Wait on and process all in-flight BIOs.  This must only be called once
5221da177e4SLinus Torvalds  * all bios have been issued so that the refcount can only decrease.
5239b81c842SSasha Levin  * This just waits for all bios to make it through dio_bio_complete.  IO
5241da177e4SLinus Torvalds  * errors are propagated through dio->io_error and should be propagated via
5251da177e4SLinus Torvalds  * dio_complete().
5261da177e4SLinus Torvalds  */
dio_await_completion(struct dio * dio)5270273201eSZach Brown static void dio_await_completion(struct dio *dio)
5280273201eSZach Brown {
5290273201eSZach Brown 	struct bio *bio;
530beb7dd86SRobert P. J. Day 	do {
5310273201eSZach Brown 		bio = dio_await_one(dio);
5321da177e4SLinus Torvalds 		if (bio)
5336d544bb4SZach Brown 			dio_bio_complete(dio, bio);
5341da177e4SLinus Torvalds 	} while (bio);
5350273201eSZach Brown }
5360273201eSZach Brown 
5370273201eSZach Brown /*
5380273201eSZach Brown  * A really large O_DIRECT read or write can generate a lot of BIOs.  So
5396d544bb4SZach Brown  * to keep the memory consumption sane we periodically reap any completed BIOs
5400273201eSZach Brown  * during the BIO generation phase.
5411da177e4SLinus Torvalds  *
5421da177e4SLinus Torvalds  * This also helps to limit the peak amount of pinned userspace memory.
5431da177e4SLinus Torvalds  */
dio_bio_reap(struct dio * dio,struct dio_submit * sdio)5441da177e4SLinus Torvalds static inline int dio_bio_reap(struct dio *dio, struct dio_submit *sdio)
5451da177e4SLinus Torvalds {
5461da177e4SLinus Torvalds 	int ret = 0;
5471da177e4SLinus Torvalds 
5481da177e4SLinus Torvalds 	if (sdio->reap_counter++ >= 64) {
5491da177e4SLinus Torvalds 		while (dio->bio_list) {
550ba253fbfSAndi Kleen 			unsigned long flags;
5511da177e4SLinus Torvalds 			struct bio *bio;
5521da177e4SLinus Torvalds 			int ret2;
5531da177e4SLinus Torvalds 
554eb28be2bSAndi Kleen 			spin_lock_irqsave(&dio->bio_lock, flags);
5551da177e4SLinus Torvalds 			bio = dio->bio_list;
5561da177e4SLinus Torvalds 			dio->bio_list = bio->bi_private;
5571da177e4SLinus Torvalds 			spin_unlock_irqrestore(&dio->bio_lock, flags);
5581da177e4SLinus Torvalds 			ret2 = blk_status_to_errno(dio_bio_complete(dio, bio));
5591da177e4SLinus Torvalds 			if (ret == 0)
5601da177e4SLinus Torvalds 				ret = ret2;
5611da177e4SLinus Torvalds 		}
5621da177e4SLinus Torvalds 		sdio->reap_counter = 0;
5631da177e4SLinus Torvalds 	}
5644e4cbee9SChristoph Hellwig 	return ret;
5651da177e4SLinus Torvalds }
5661da177e4SLinus Torvalds 
dio_set_defer_completion(struct dio * dio)5671da177e4SLinus Torvalds static int dio_set_defer_completion(struct dio *dio)
568eb28be2bSAndi Kleen {
5691da177e4SLinus Torvalds 	struct super_block *sb = dio->inode->i_sb;
5701da177e4SLinus Torvalds 
5711da177e4SLinus Torvalds 	if (dio->defer_completion)
5721da177e4SLinus Torvalds 		return 0;
5737b7a8665SChristoph Hellwig 	dio->defer_completion = true;
5747b7a8665SChristoph Hellwig 	if (!sb->s_dio_done_wq)
5757b7a8665SChristoph Hellwig 		return sb_init_dio_done_wq(sb);
5767b7a8665SChristoph Hellwig 	return 0;
5777b7a8665SChristoph Hellwig }
5787b7a8665SChristoph Hellwig 
5797b7a8665SChristoph Hellwig /*
5807b7a8665SChristoph Hellwig  * Call into the fs to map some more disk blocks.  We record the current number
5817b7a8665SChristoph Hellwig  * of available blocks at sdio->blocks_available.  These are in units of the
5827b7a8665SChristoph Hellwig  * fs blocksize, i_blocksize(inode).
5837b7a8665SChristoph Hellwig  *
5847b7a8665SChristoph Hellwig  * The fs is allowed to map lots of blocks at once.  If it wants to do that,
5857b7a8665SChristoph Hellwig  * it uses the passed inode-relative block number as the file offset, as usual.
5861da177e4SLinus Torvalds  *
587eb28be2bSAndi Kleen  * get_block() is passed the number of i_blkbits-sized blocks which direct_io
58893407472SFabian Frederick  * has remaining to do.  The fs should not map more than this number of blocks.
5891da177e4SLinus Torvalds  *
5901da177e4SLinus Torvalds  * If the fs has mapped a lot of blocks, it should populate bh->b_size to
5911da177e4SLinus Torvalds  * indicate how much contiguous disk space has been made available at
5921da177e4SLinus Torvalds  * bh->b_blocknr.
5931d8fa7a2SBadari Pulavarty  *
5941da177e4SLinus Torvalds  * If *any* of the mapped blocks are new, then the fs must set buffer_new().
5951da177e4SLinus Torvalds  * This isn't very efficient...
5961da177e4SLinus Torvalds  *
5971da177e4SLinus Torvalds  * In the case of filesystem holes: the fs may return an arbitrarily-large
5981da177e4SLinus Torvalds  * hole by returning an appropriate value in b_size and by clearing
5991da177e4SLinus Torvalds  * buffer_mapped().  However the direct-io code will only process holes one
6001da177e4SLinus Torvalds  * block at a time - it will repeatedly call get_block() as it walks the hole.
6011da177e4SLinus Torvalds  */
get_more_blocks(struct dio * dio,struct dio_submit * sdio,struct buffer_head * map_bh)6021da177e4SLinus Torvalds static int get_more_blocks(struct dio *dio, struct dio_submit *sdio,
6031da177e4SLinus Torvalds 			   struct buffer_head *map_bh)
6041da177e4SLinus Torvalds {
6051da177e4SLinus Torvalds 	const enum req_op dio_op = dio->opf & REQ_OP_MASK;
6061d8fa7a2SBadari Pulavarty 	int ret;
6071da177e4SLinus Torvalds 	sector_t fs_startblk;	/* Into file, in filesystem-sized blocks */
60818772641SAndi Kleen 	sector_t fs_endblk;	/* Into file, in filesystem-sized blocks */
60918772641SAndi Kleen 	unsigned long fs_count;	/* Number of filesystem-sized blocks */
6101da177e4SLinus Torvalds 	int create;
611c6293eacSBart Van Assche 	unsigned int i_blkbits = sdio->blkbits + sdio->blkfactor;
6121da177e4SLinus Torvalds 	loff_t i_size;
6131da177e4SLinus Torvalds 
614ae55e1aaSTao Ma 	/*
6151da177e4SLinus Torvalds 	 * If there was a memory error and we've overwritten all the
6161da177e4SLinus Torvalds 	 * mapped blocks then we can now return that memory error
617ab73857eSLinus Torvalds 	 */
6188b9433ebSErnesto A. Fernández 	ret = dio->page_errors;
6191da177e4SLinus Torvalds 	if (ret == 0) {
6201da177e4SLinus Torvalds 		BUG_ON(sdio->block_in_file >= sdio->final_block_in_request);
6211da177e4SLinus Torvalds 		fs_startblk = sdio->block_in_file >> sdio->blkfactor;
6221da177e4SLinus Torvalds 		fs_endblk = (sdio->final_block_in_request - 1) >>
6231da177e4SLinus Torvalds 					sdio->blkfactor;
6241da177e4SLinus Torvalds 		fs_count = fs_endblk - fs_startblk + 1;
6251da177e4SLinus Torvalds 
626eb28be2bSAndi Kleen 		map_bh->b_state = 0;
627eb28be2bSAndi Kleen 		map_bh->b_size = fs_count << i_blkbits;
628ae55e1aaSTao Ma 
629ae55e1aaSTao Ma 		/*
630ae55e1aaSTao Ma 		 * For writes that could fill holes inside i_size on a
6311da177e4SLinus Torvalds 		 * DIO_SKIP_HOLES filesystem we forbid block creations: only
6323c674e74SNathan Scott 		 * overwrites are permitted. We will return early to the caller
633ab73857eSLinus Torvalds 		 * once we see an unmapped buffer head returned, and the caller
6343c674e74SNathan Scott 		 * will fall back to buffered I/O.
6355fe878aeSChristoph Hellwig 		 *
6369ecd10b7SEryu Guan 		 * Otherwise the decision is left to the get_blocks method,
6379ecd10b7SEryu Guan 		 * which may decide to handle it or also return an unmapped
6389ecd10b7SEryu Guan 		 * buffer head.
6399ecd10b7SEryu Guan 		 */
6409ecd10b7SEryu Guan 		create = dio_op == REQ_OP_WRITE;
6415fe878aeSChristoph Hellwig 		if (dio->flags & DIO_SKIP_HOLES) {
6425fe878aeSChristoph Hellwig 			i_size = i_size_read(dio->inode);
6435fe878aeSChristoph Hellwig 			if (i_size && fs_startblk <= (i_size - 1) >> i_blkbits)
6445fe878aeSChristoph Hellwig 				create = 0;
6455fe878aeSChristoph Hellwig 		}
646c6293eacSBart Van Assche 
6475fe878aeSChristoph Hellwig 		ret = (*sdio->get_block)(dio->inode, fs_startblk,
6488b9433ebSErnesto A. Fernández 						map_bh, create);
6498b9433ebSErnesto A. Fernández 
6501da177e4SLinus Torvalds 		/* Store for completion */
6511da177e4SLinus Torvalds 		dio->private = map_bh->b_private;
6523c674e74SNathan Scott 
653eb28be2bSAndi Kleen 		if (ret == 0 && buffer_defer_completion(map_bh))
6541da177e4SLinus Torvalds 			ret = dio_set_defer_completion(dio);
65518772641SAndi Kleen 	}
65618772641SAndi Kleen 	return ret;
65718772641SAndi Kleen }
6587b7a8665SChristoph Hellwig 
6597b7a8665SChristoph Hellwig /*
6607b7a8665SChristoph Hellwig  * There is no bio.  Make one now.
6611da177e4SLinus Torvalds  */
dio_new_bio(struct dio * dio,struct dio_submit * sdio,sector_t start_sector,struct buffer_head * map_bh)6621da177e4SLinus Torvalds static inline int dio_new_bio(struct dio *dio, struct dio_submit *sdio,
6631da177e4SLinus Torvalds 		sector_t start_sector, struct buffer_head *map_bh)
6641da177e4SLinus Torvalds {
6651da177e4SLinus Torvalds 	sector_t sector;
6661da177e4SLinus Torvalds 	int ret, nr_pages;
6671da177e4SLinus Torvalds 
668ba253fbfSAndi Kleen 	ret = dio_bio_reap(dio, sdio);
66918772641SAndi Kleen 	if (ret)
6701da177e4SLinus Torvalds 		goto out;
6711da177e4SLinus Torvalds 	sector = start_sector << (sdio->blkbits - 9);
6721da177e4SLinus Torvalds 	nr_pages = bio_max_segs(sdio->pages_in_io);
6731da177e4SLinus Torvalds 	BUG_ON(nr_pages <= 0);
674eb28be2bSAndi Kleen 	dio_bio_alloc(dio, sdio, map_bh->b_bdev, sector, nr_pages);
6751da177e4SLinus Torvalds 	sdio->boundary = 0;
6761da177e4SLinus Torvalds out:
677eb28be2bSAndi Kleen 	return ret;
6785f7136dbSMatthew Wilcox (Oracle) }
6791da177e4SLinus Torvalds 
68018772641SAndi Kleen /*
681eb28be2bSAndi Kleen  * Attempt to put the current chunk of 'cur_page' into the current BIO.  If
6821da177e4SLinus Torvalds  * that was successful then update final_block_in_bio and take a ref against
6831da177e4SLinus Torvalds  * the just-added page.
6841da177e4SLinus Torvalds  *
6851da177e4SLinus Torvalds  * Return zero on success.  Non-zero means the caller needs to start a new BIO.
6861da177e4SLinus Torvalds  */
dio_bio_add_page(struct dio * dio,struct dio_submit * sdio)6871da177e4SLinus Torvalds static inline int dio_bio_add_page(struct dio *dio, struct dio_submit *sdio)
6881da177e4SLinus Torvalds {
6891da177e4SLinus Torvalds 	int ret;
6901da177e4SLinus Torvalds 
6911da177e4SLinus Torvalds 	ret = bio_add_page(sdio->bio, sdio->cur_page,
6921da177e4SLinus Torvalds 			sdio->cur_page_len, sdio->cur_page_offset);
6931ccf164eSDavid Howells 	if (ret == sdio->cur_page_len) {
6941da177e4SLinus Torvalds 		/*
6951da177e4SLinus Torvalds 		 * Decrement count only, if we are done with this page
6961da177e4SLinus Torvalds 		 */
697eb28be2bSAndi Kleen 		if ((sdio->cur_page_len + sdio->cur_page_offset) == PAGE_SIZE)
698eb28be2bSAndi Kleen 			sdio->pages_in_io--;
699eb28be2bSAndi Kleen 		dio_pin_page(dio, sdio->cur_page);
7001da177e4SLinus Torvalds 		sdio->final_block_in_bio = sdio->cur_page_block +
7011da177e4SLinus Torvalds 			(sdio->cur_page_len >> sdio->blkbits);
7021da177e4SLinus Torvalds 		ret = 0;
703eb28be2bSAndi Kleen 	} else {
704eb28be2bSAndi Kleen 		ret = 1;
7051ccf164eSDavid Howells 	}
706eb28be2bSAndi Kleen 	return ret;
707eb28be2bSAndi Kleen }
7081da177e4SLinus Torvalds 
7091da177e4SLinus Torvalds /*
7101da177e4SLinus Torvalds  * Put cur_page under IO.  The section of cur_page which is described by
7111da177e4SLinus Torvalds  * cur_page_offset,cur_page_len is put into a BIO.  The section of cur_page
7121da177e4SLinus Torvalds  * starts on-disk at cur_page_block.
7131da177e4SLinus Torvalds  *
7141da177e4SLinus Torvalds  * We take a ref against the page here (on behalf of its presence in the bio).
7151da177e4SLinus Torvalds  *
7161da177e4SLinus Torvalds  * The caller of this function is responsible for removing cur_page from the
7171da177e4SLinus Torvalds  * dio, and for dropping the refcount which came from that presence.
7181da177e4SLinus Torvalds  */
dio_send_cur_page(struct dio * dio,struct dio_submit * sdio,struct buffer_head * map_bh)7191da177e4SLinus Torvalds static inline int dio_send_cur_page(struct dio *dio, struct dio_submit *sdio,
7201da177e4SLinus Torvalds 		struct buffer_head *map_bh)
7211da177e4SLinus Torvalds {
7221da177e4SLinus Torvalds 	int ret = 0;
7231da177e4SLinus Torvalds 
7241da177e4SLinus Torvalds 	if (sdio->bio) {
725ba253fbfSAndi Kleen 		loff_t cur_offset = sdio->cur_page_fs_offset;
72618772641SAndi Kleen 		loff_t bio_next_offset = sdio->logical_offset_in_bio +
7271da177e4SLinus Torvalds 			sdio->bio->bi_iter.bi_size;
7281da177e4SLinus Torvalds 
7291da177e4SLinus Torvalds 		/*
730eb28be2bSAndi Kleen 		 * See whether this new request is contiguous with the old.
731eb28be2bSAndi Kleen 		 *
732eb28be2bSAndi Kleen 		 * Btrfs cannot handle having logically non-contiguous requests
7334f024f37SKent Overstreet 		 * submitted.  For example if you have
734c2c6ca41SJosef Bacik 		 *
7351da177e4SLinus Torvalds 		 * Logical:  [0-4095][HOLE][8192-12287]
736c2c6ca41SJosef Bacik 		 * Physical: [0-4095]      [4096-8191]
737c2c6ca41SJosef Bacik 		 *
738f0940ceeSNamhyung Kim 		 * We cannot submit those pages together as one BIO.  So if our
739f0940ceeSNamhyung Kim 		 * current logical offset in the file does not equal what would
740c2c6ca41SJosef Bacik 		 * be the next logical offset in the bio, submit the bio we
741c2c6ca41SJosef Bacik 		 * have.
742f0940ceeSNamhyung Kim 		 */
743c2c6ca41SJosef Bacik 		if (sdio->final_block_in_bio != sdio->cur_page_block ||
744c2c6ca41SJosef Bacik 		    cur_offset != bio_next_offset)
745c2c6ca41SJosef Bacik 			dio_bio_submit(dio, sdio);
746c2c6ca41SJosef Bacik 	}
747c2c6ca41SJosef Bacik 
7481da177e4SLinus Torvalds 	if (sdio->bio == NULL) {
749eb28be2bSAndi Kleen 		ret = dio_new_bio(dio, sdio, sdio->cur_page_block, map_bh);
750c2c6ca41SJosef Bacik 		if (ret)
751eb28be2bSAndi Kleen 			goto out;
7521da177e4SLinus Torvalds 	}
7531da177e4SLinus Torvalds 
754eb28be2bSAndi Kleen 	if (dio_bio_add_page(dio, sdio) != 0) {
75518772641SAndi Kleen 		dio_bio_submit(dio, sdio);
7561da177e4SLinus Torvalds 		ret = dio_new_bio(dio, sdio, sdio->cur_page_block, map_bh);
7571da177e4SLinus Torvalds 		if (ret == 0) {
7581da177e4SLinus Torvalds 			ret = dio_bio_add_page(dio, sdio);
7591da177e4SLinus Torvalds 			BUG_ON(ret != 0);
7601ccf164eSDavid Howells 		}
761eb28be2bSAndi Kleen 	}
76218772641SAndi Kleen out:
7631da177e4SLinus Torvalds 	return ret;
7641ccf164eSDavid Howells }
7651da177e4SLinus Torvalds 
7661da177e4SLinus Torvalds /*
7671da177e4SLinus Torvalds  * An autonomous function to put a chunk of a page under deferred IO.
7681da177e4SLinus Torvalds  *
7691da177e4SLinus Torvalds  * The caller doesn't actually know (or care) whether this piece of page is in
7701da177e4SLinus Torvalds  * a BIO, or is under IO or whatever.  We just take care of all possible
7711da177e4SLinus Torvalds  * situations here.  The separation between the logic of do_direct_IO() and
7721da177e4SLinus Torvalds  * that of submit_page_section() is important for clarity.  Please don't break.
7731da177e4SLinus Torvalds  *
7741da177e4SLinus Torvalds  * The chunk of page starts on-disk at blocknr.
7751da177e4SLinus Torvalds  *
7761da177e4SLinus Torvalds  * We perform deferred IO, by recording the last-submitted page inside our
7771da177e4SLinus Torvalds  * private part of the dio structure.  If possible, we just expand the IO
7781da177e4SLinus Torvalds  * across that page here.
7791da177e4SLinus Torvalds  *
7801da177e4SLinus Torvalds  * If that doesn't work out then we put the old page into the bio and add this
7811da177e4SLinus Torvalds  * page to the dio instead.
7821da177e4SLinus Torvalds  */
7831da177e4SLinus Torvalds static inline int
submit_page_section(struct dio * dio,struct dio_submit * sdio,struct page * page,unsigned offset,unsigned len,sector_t blocknr,struct buffer_head * map_bh)7841da177e4SLinus Torvalds submit_page_section(struct dio *dio, struct dio_submit *sdio, struct page *page,
7851da177e4SLinus Torvalds 		    unsigned offset, unsigned len, sector_t blocknr,
7861da177e4SLinus Torvalds 		    struct buffer_head *map_bh)
7871da177e4SLinus Torvalds {
7881da177e4SLinus Torvalds 	const enum req_op dio_op = dio->opf & REQ_OP_MASK;
789ba253fbfSAndi Kleen 	int ret = 0;
790eb28be2bSAndi Kleen 	int boundary = sdio->boundary;	/* dio_send_cur_page may clear it */
79118772641SAndi Kleen 
79218772641SAndi Kleen 	if (dio_op == REQ_OP_WRITE) {
7931da177e4SLinus Torvalds 		/*
794c6293eacSBart Van Assche 		 * Read accounting is performed in submit_bio()
7951da177e4SLinus Torvalds 		 */
796df41872bSJack Qiu 		task_io_account_write(len);
7971da177e4SLinus Torvalds 	}
798c6293eacSBart Van Assche 
79998c4d57dSAndrew Morton 	/*
80098c4d57dSAndrew Morton 	 * Can we just grow the current page's presence in the dio?
80198c4d57dSAndrew Morton 	 */
80298c4d57dSAndrew Morton 	if (sdio->cur_page == page &&
80398c4d57dSAndrew Morton 	    sdio->cur_page_offset + sdio->cur_page_len == offset &&
80498c4d57dSAndrew Morton 	    sdio->cur_page_block +
8051da177e4SLinus Torvalds 	    (sdio->cur_page_len >> sdio->blkbits) == blocknr) {
8061da177e4SLinus Torvalds 		sdio->cur_page_len += len;
8071da177e4SLinus Torvalds 		goto out;
808eb28be2bSAndi Kleen 	}
809eb28be2bSAndi Kleen 
810eb28be2bSAndi Kleen 	/*
811eb28be2bSAndi Kleen 	 * If there's a deferred page already there then send it.
812eb28be2bSAndi Kleen 	 */
8131da177e4SLinus Torvalds 	if (sdio->cur_page) {
8141da177e4SLinus Torvalds 		ret = dio_send_cur_page(dio, sdio, map_bh);
8151da177e4SLinus Torvalds 		dio_unpin_page(dio, sdio->cur_page);
8161da177e4SLinus Torvalds 		sdio->cur_page = NULL;
8171da177e4SLinus Torvalds 		if (ret)
8181da177e4SLinus Torvalds 			return ret;
819eb28be2bSAndi Kleen 	}
82018772641SAndi Kleen 
8211ccf164eSDavid Howells 	dio_pin_page(dio, page);		/* It is in dio */
822eb28be2bSAndi Kleen 	sdio->cur_page = page;
8231da177e4SLinus Torvalds 	sdio->cur_page_offset = offset;
824b1058b98SJan Kara 	sdio->cur_page_len = len;
8251da177e4SLinus Torvalds 	sdio->cur_page_block = blocknr;
8261da177e4SLinus Torvalds 	sdio->cur_page_fs_offset = sdio->block_in_file << sdio->blkbits;
8271ccf164eSDavid Howells out:
828eb28be2bSAndi Kleen 	/*
829eb28be2bSAndi Kleen 	 * If boundary then we want to schedule the IO now to
830eb28be2bSAndi Kleen 	 * avoid metadata seeks.
831eb28be2bSAndi Kleen 	 */
832eb28be2bSAndi Kleen 	if (boundary) {
8331da177e4SLinus Torvalds 		ret = dio_send_cur_page(dio, sdio, map_bh);
834b1058b98SJan Kara 		if (sdio->bio)
835df41872bSJack Qiu 			dio_bio_submit(dio, sdio);
836b1058b98SJan Kara 		dio_unpin_page(dio, sdio->cur_page);
837b1058b98SJan Kara 		sdio->cur_page = NULL;
838df41872bSJack Qiu 	}
839b1058b98SJan Kara 	return ret;
840899f0429SAndreas Gruenbacher }
841b1058b98SJan Kara 
8421ccf164eSDavid Howells /*
843b1058b98SJan Kara  * If we are not writing the entire block and get_block() allocated
844b1058b98SJan Kara  * the block for us, we need to fill-in the unused portion of the
8451da177e4SLinus Torvalds  * block with zeros. This happens only if user-buffer, fileoffset or
8461da177e4SLinus Torvalds  * io length is not filesystem block-size multiple.
8471da177e4SLinus Torvalds  *
8481da177e4SLinus Torvalds  * `end' is zero if we're doing the start of the IO, 1 at the end of the
8491da177e4SLinus Torvalds  * IO.
8501da177e4SLinus Torvalds  */
dio_zero_block(struct dio * dio,struct dio_submit * sdio,int end,struct buffer_head * map_bh)8511da177e4SLinus Torvalds static inline void dio_zero_block(struct dio *dio, struct dio_submit *sdio,
8521da177e4SLinus Torvalds 		int end, struct buffer_head *map_bh)
8531da177e4SLinus Torvalds {
8541da177e4SLinus Torvalds 	unsigned dio_blocks_per_fs_block;
8551da177e4SLinus Torvalds 	unsigned this_chunk_blocks;	/* In dio_blocks */
8561da177e4SLinus Torvalds 	unsigned this_chunk_bytes;
857ba253fbfSAndi Kleen 	struct page *page;
858ba253fbfSAndi Kleen 
8591da177e4SLinus Torvalds 	sdio->start_zero_done = 1;
8601da177e4SLinus Torvalds 	if (!sdio->blkfactor || !buffer_new(map_bh))
8611da177e4SLinus Torvalds 		return;
8621da177e4SLinus Torvalds 
8631da177e4SLinus Torvalds 	dio_blocks_per_fs_block = 1 << sdio->blkfactor;
8641da177e4SLinus Torvalds 	this_chunk_blocks = sdio->block_in_file & (dio_blocks_per_fs_block - 1);
865eb28be2bSAndi Kleen 
86618772641SAndi Kleen 	if (!this_chunk_blocks)
8671da177e4SLinus Torvalds 		return;
8681da177e4SLinus Torvalds 
869eb28be2bSAndi Kleen 	/*
870eb28be2bSAndi Kleen 	 * We need to zero out part of an fs block.  It is either at the
8711da177e4SLinus Torvalds 	 * beginning or the end of the fs block.
8721da177e4SLinus Torvalds 	 */
8731da177e4SLinus Torvalds 	if (end)
8741da177e4SLinus Torvalds 		this_chunk_blocks = dio_blocks_per_fs_block - this_chunk_blocks;
8751da177e4SLinus Torvalds 
8761da177e4SLinus Torvalds 	this_chunk_bytes = this_chunk_blocks << sdio->blkbits;
8771da177e4SLinus Torvalds 
8781da177e4SLinus Torvalds 	page = ZERO_PAGE(0);
8791da177e4SLinus Torvalds 	if (submit_page_section(dio, sdio, page, 0, this_chunk_bytes,
8801da177e4SLinus Torvalds 				sdio->next_block_for_io, map_bh))
8811da177e4SLinus Torvalds 		return;
882eb28be2bSAndi Kleen 
8831da177e4SLinus Torvalds 	sdio->next_block_for_io += this_chunk_blocks;
884557ed1faSNick Piggin }
885eb28be2bSAndi Kleen 
88618772641SAndi Kleen /*
8871da177e4SLinus Torvalds  * Walk the user pages, and the file, mapping blocks to disk and generating
8881da177e4SLinus Torvalds  * a sequence of (page,offset,len,block) mappings.  These mappings are injected
889eb28be2bSAndi Kleen  * into submit_page_section(), which takes care of the next stage of submission
8901da177e4SLinus Torvalds  *
8911da177e4SLinus Torvalds  * Direct IO against a blockdev is different from a file.  Because we can
8921da177e4SLinus Torvalds  * happily perform page-sized but 512-byte aligned IOs.  It is important that
8931da177e4SLinus Torvalds  * blockdev IO be able to have fine alignment and large sizes.
8941da177e4SLinus Torvalds  *
8951da177e4SLinus Torvalds  * So what we do is to permit the ->get_block function to populate bh.b_size
8961da177e4SLinus Torvalds  * with the size of IO which is permitted at this offset and this i_blkbits.
8971da177e4SLinus Torvalds  *
8981da177e4SLinus Torvalds  * For best results, the blockdev should be set up with 512-byte i_blkbits and
8991da177e4SLinus Torvalds  * it should set b_size to PAGE_SIZE or more inside get_block().  This gives
9001da177e4SLinus Torvalds  * fine alignment but still allows this function to work in PAGE_SIZE units.
9011d8fa7a2SBadari Pulavarty  */
do_direct_IO(struct dio * dio,struct dio_submit * sdio,struct buffer_head * map_bh)9021da177e4SLinus Torvalds static int do_direct_IO(struct dio *dio, struct dio_submit *sdio,
9031da177e4SLinus Torvalds 			struct buffer_head *map_bh)
9041da177e4SLinus Torvalds {
9051d8fa7a2SBadari Pulavarty 	const enum req_op dio_op = dio->opf & REQ_OP_MASK;
9061da177e4SLinus Torvalds 	const unsigned blkbits = sdio->blkbits;
9071da177e4SLinus Torvalds 	const unsigned i_blkbits = blkbits + sdio->blkfactor;
90818772641SAndi Kleen 	int ret = 0;
90918772641SAndi Kleen 
9101da177e4SLinus Torvalds 	while (sdio->block_in_file < sdio->final_block_in_request) {
911c6293eacSBart Van Assche 		struct page *page;
912eb28be2bSAndi Kleen 		size_t from, to;
913dd545b52SChandan Rajendra 
9141da177e4SLinus Torvalds 		page = dio_get_page(dio, sdio);
9151da177e4SLinus Torvalds 		if (IS_ERR(page)) {
916eb28be2bSAndi Kleen 			ret = PTR_ERR(page);
9177b2c99d1SAl Viro 			goto out;
9187b2c99d1SAl Viro 		}
9196fcc5420SBoaz Harrosh 		from = sdio->head ? 0 : sdio->from;
9206fcc5420SBoaz Harrosh 		to = (sdio->head == sdio->tail - 1) ? sdio->to : PAGE_SIZE;
9211da177e4SLinus Torvalds 		sdio->head++;
9221da177e4SLinus Torvalds 
9231da177e4SLinus Torvalds 		while (from < to) {
9241da177e4SLinus Torvalds 			unsigned this_chunk_bytes;	/* # of bytes mapped */
9256fcc5420SBoaz Harrosh 			unsigned this_chunk_blocks;	/* # of blocks */
9266fcc5420SBoaz Harrosh 			unsigned u;
9276fcc5420SBoaz Harrosh 
9281da177e4SLinus Torvalds 			if (sdio->blocks_available == 0) {
9297b2c99d1SAl Viro 				/*
9301da177e4SLinus Torvalds 				 * Need to go and map some more disk
9311da177e4SLinus Torvalds 				 */
9321da177e4SLinus Torvalds 				unsigned long blkmask;
9331da177e4SLinus Torvalds 				unsigned long dio_remainder;
934eb28be2bSAndi Kleen 
9351da177e4SLinus Torvalds 				ret = get_more_blocks(dio, sdio, map_bh);
9361da177e4SLinus Torvalds 				if (ret) {
9371da177e4SLinus Torvalds 					dio_unpin_page(dio, page);
9381da177e4SLinus Torvalds 					goto out;
9391da177e4SLinus Torvalds 				}
9401da177e4SLinus Torvalds 				if (!buffer_mapped(map_bh))
94118772641SAndi Kleen 					goto do_holes;
9421da177e4SLinus Torvalds 
9431ccf164eSDavid Howells 				sdio->blocks_available =
9441da177e4SLinus Torvalds 						map_bh->b_size >> blkbits;
9451da177e4SLinus Torvalds 				sdio->next_block_for_io =
9461da177e4SLinus Torvalds 					map_bh->b_blocknr << sdio->blkfactor;
9471da177e4SLinus Torvalds 				if (buffer_new(map_bh)) {
9481da177e4SLinus Torvalds 					clean_bdev_aliases(
949eb28be2bSAndi Kleen 						map_bh->b_bdev,
950f734c89cSJan Kara 						map_bh->b_blocknr,
951eb28be2bSAndi Kleen 						map_bh->b_size >> i_blkbits);
952eb28be2bSAndi Kleen 				}
953f734c89cSJan Kara 
954f734c89cSJan Kara 				if (!sdio->blkfactor)
955f734c89cSJan Kara 					goto do_holes;
956f734c89cSJan Kara 
957dd545b52SChandan Rajendra 				blkmask = (1 << sdio->blkfactor) - 1;
958f734c89cSJan Kara 				dio_remainder = (sdio->block_in_file & blkmask);
9591da177e4SLinus Torvalds 
960eb28be2bSAndi Kleen 				/*
9611da177e4SLinus Torvalds 				 * If we are at the start of IO and that IO
9621da177e4SLinus Torvalds 				 * starts partway into a fs-block,
963eb28be2bSAndi Kleen 				 * dio_remainder will be non-zero.  If the IO
964eb28be2bSAndi Kleen 				 * is a read then we can simply advance the IO
9651da177e4SLinus Torvalds 				 * cursor to the first block which is to be
9661da177e4SLinus Torvalds 				 * read.  But if the IO is a write and the
9671da177e4SLinus Torvalds 				 * block was newly allocated we cannot do that;
9681da177e4SLinus Torvalds 				 * the start of the fs block must be zeroed out
9691da177e4SLinus Torvalds 				 * on-disk
9701da177e4SLinus Torvalds 				 */
9711da177e4SLinus Torvalds 				if (!buffer_new(map_bh))
9721da177e4SLinus Torvalds 					sdio->next_block_for_io += dio_remainder;
9731da177e4SLinus Torvalds 				sdio->blocks_available -= dio_remainder;
9741da177e4SLinus Torvalds 			}
9751da177e4SLinus Torvalds do_holes:
9761da177e4SLinus Torvalds 			/* Handle holes */
9771da177e4SLinus Torvalds 			if (!buffer_mapped(map_bh)) {
978eb28be2bSAndi Kleen 				loff_t i_size_aligned;
979eb28be2bSAndi Kleen 
9801da177e4SLinus Torvalds 				/* AKPM: eargh, -ENOTBLK is a hack */
9811da177e4SLinus Torvalds 				if (dio_op == REQ_OP_WRITE) {
9821da177e4SLinus Torvalds 					dio_unpin_page(dio, page);
9831da177e4SLinus Torvalds 					return -ENOTBLK;
98435dc8161SJeff Moyer 				}
9851da177e4SLinus Torvalds 
9861da177e4SLinus Torvalds 				/*
987c6293eacSBart Van Assche 				 * Be sure to account for a partial block as the
9881ccf164eSDavid Howells 				 * last block in the file
9891da177e4SLinus Torvalds 				 */
9901da177e4SLinus Torvalds 				i_size_aligned = ALIGN(i_size_read(dio->inode),
9911da177e4SLinus Torvalds 							1 << blkbits);
99235dc8161SJeff Moyer 				if (sdio->block_in_file >=
99335dc8161SJeff Moyer 						i_size_aligned >> blkbits) {
99435dc8161SJeff Moyer 					/* We hit eof */
99535dc8161SJeff Moyer 					dio_unpin_page(dio, page);
99635dc8161SJeff Moyer 					goto out;
99735dc8161SJeff Moyer 				}
998eb28be2bSAndi Kleen 				zero_user(page, from, 1 << blkbits);
99935dc8161SJeff Moyer 				sdio->block_in_file++;
10001da177e4SLinus Torvalds 				from += 1 << blkbits;
10011ccf164eSDavid Howells 				dio->result += 1 << blkbits;
10021da177e4SLinus Torvalds 				goto next_block;
10031da177e4SLinus Torvalds 			}
10047b2c99d1SAl Viro 
1005eb28be2bSAndi Kleen 			/*
10067b2c99d1SAl Viro 			 * If we're performing IO which has an alignment which
10073320c60bSAl Viro 			 * is finer than the underlying fs, go check to see if
10081da177e4SLinus Torvalds 			 * we must zero out the start of this block.
10091da177e4SLinus Torvalds 			 */
10101da177e4SLinus Torvalds 			if (unlikely(sdio->blkfactor && !sdio->start_zero_done))
10111da177e4SLinus Torvalds 				dio_zero_block(dio, sdio, 0, map_bh);
10121da177e4SLinus Torvalds 
10131da177e4SLinus Torvalds 			/*
10141da177e4SLinus Torvalds 			 * Work out, in this_chunk_blocks, how much disk we
10151da177e4SLinus Torvalds 			 * can add to this page
1016eb28be2bSAndi Kleen 			 */
101718772641SAndi Kleen 			this_chunk_blocks = sdio->blocks_available;
10181da177e4SLinus Torvalds 			u = (to - from) >> blkbits;
10191da177e4SLinus Torvalds 			if (this_chunk_blocks > u)
10201da177e4SLinus Torvalds 				this_chunk_blocks = u;
10211da177e4SLinus Torvalds 			u = sdio->final_block_in_request - sdio->block_in_file;
10221da177e4SLinus Torvalds 			if (this_chunk_blocks > u)
1023eb28be2bSAndi Kleen 				this_chunk_blocks = u;
10247b2c99d1SAl Viro 			this_chunk_bytes = this_chunk_blocks << blkbits;
10251da177e4SLinus Torvalds 			BUG_ON(this_chunk_bytes == 0);
10261da177e4SLinus Torvalds 
1027eb28be2bSAndi Kleen 			if (this_chunk_blocks == sdio->blocks_available)
10281da177e4SLinus Torvalds 				sdio->boundary = buffer_boundary(map_bh);
10291da177e4SLinus Torvalds 			ret = submit_page_section(dio, sdio, page,
10301da177e4SLinus Torvalds 						  from,
10311da177e4SLinus Torvalds 						  this_chunk_bytes,
10321da177e4SLinus Torvalds 						  sdio->next_block_for_io,
1033092c8d46SJan Kara 						  map_bh);
1034eb28be2bSAndi Kleen 			if (ret) {
1035eb28be2bSAndi Kleen 				dio_unpin_page(dio, page);
10367b2c99d1SAl Viro 				goto out;
1037eb28be2bSAndi Kleen 			}
103818772641SAndi Kleen 			sdio->next_block_for_io += this_chunk_blocks;
103918772641SAndi Kleen 
10401da177e4SLinus Torvalds 			sdio->block_in_file += this_chunk_blocks;
10411ccf164eSDavid Howells 			from += this_chunk_bytes;
10421da177e4SLinus Torvalds 			dio->result += this_chunk_bytes;
10431da177e4SLinus Torvalds 			sdio->blocks_available -= this_chunk_blocks;
1044eb28be2bSAndi Kleen next_block:
10451da177e4SLinus Torvalds 			BUG_ON(sdio->block_in_file > sdio->final_block_in_request);
1046eb28be2bSAndi Kleen 			if (sdio->block_in_file == sdio->final_block_in_request)
10477b2c99d1SAl Viro 				break;
10487b2c99d1SAl Viro 		}
1049eb28be2bSAndi Kleen 
10501da177e4SLinus Torvalds 		/* Drop the pin which was taken in get_user_pages() */
1051eb28be2bSAndi Kleen 		dio_unpin_page(dio, page);
1052eb28be2bSAndi Kleen 	}
10531da177e4SLinus Torvalds out:
10541da177e4SLinus Torvalds 	return ret;
10551da177e4SLinus Torvalds }
10561ccf164eSDavid Howells 
drop_refcount(struct dio * dio)10571ccf164eSDavid Howells static inline int drop_refcount(struct dio *dio)
10581da177e4SLinus Torvalds {
10591da177e4SLinus Torvalds 	int ret2;
10601da177e4SLinus Torvalds 	unsigned long flags;
10611da177e4SLinus Torvalds 
10621da177e4SLinus Torvalds 	/*
1063847cc637SAndi Kleen 	 * Sync will always be dropping the final ref and completing the
10641da177e4SLinus Torvalds 	 * operation.  AIO can if it was a broken operation described above or
1065847cc637SAndi Kleen 	 * in fact if all the bios race to complete before we get here.  In
10665eb6c7a2SZach Brown 	 * that case dio_complete() translates the EIOCBQUEUED into the proper
106720258b2bSZach Brown 	 * return code that the caller will hand to ->complete().
10681da177e4SLinus Torvalds 	 *
10698459d86aSZach Brown 	 * This is managed by the bio_lock instead of being an atomic_t so that
10705eb6c7a2SZach Brown 	 * completion paths can drop their ref and use the remaining count to
10715eb6c7a2SZach Brown 	 * decide to wake the submission path atomically.
10725eb6c7a2SZach Brown 	 */
107304b2fa9fSChristoph Hellwig 	spin_lock_irqsave(&dio->bio_lock, flags);
10745eb6c7a2SZach Brown 	ret2 = --dio->refcount;
10755eb6c7a2SZach Brown 	spin_unlock_irqrestore(&dio->bio_lock, flags);
10765eb6c7a2SZach Brown 	return ret2;
10775eb6c7a2SZach Brown }
10781da177e4SLinus Torvalds 
10795eb6c7a2SZach Brown /*
10805eb6c7a2SZach Brown  * This is a library function for use by filesystem drivers.
10815eb6c7a2SZach Brown  *
1082847cc637SAndi Kleen  * The locking rules are governed by the flags parameter:
10831da177e4SLinus Torvalds  *  - if the flags value contains DIO_LOCKING we use a fancy locking
10841da177e4SLinus Torvalds  *    scheme for dumb filesystems.
1085eafdc7d1SChristoph Hellwig  *    For writes this function is called under i_mutex and returns with
1086eafdc7d1SChristoph Hellwig  *    i_mutex held, for reads, i_mutex is not held on entry, but it is
1087eafdc7d1SChristoph Hellwig  *    taken and dropped again before returning.
1088eafdc7d1SChristoph Hellwig  *  - if the flags value does NOT contain DIO_LOCKING we don't use any
1089eafdc7d1SChristoph Hellwig  *    internal locking but rather rely on the filesystem to synchronize
1090eafdc7d1SChristoph Hellwig  *    direct I/O reads/writes versus each other and truncate.
1091eafdc7d1SChristoph Hellwig  *
1092eafdc7d1SChristoph Hellwig  * To help with locking against truncate we incremented the i_dio_count
1093eafdc7d1SChristoph Hellwig  * counter before starting direct I/O, and decrement it once we are done.
1094eafdc7d1SChristoph Hellwig  * Truncate can wait for it to reach zero to provide exclusion.  It is
1095eafdc7d1SChristoph Hellwig  * expected that filesystem provide exclusion between new direct I/O
1096eafdc7d1SChristoph Hellwig  * and truncates.  For DIO_LOCKING filesystems this is done by i_mutex,
1097df2d6f26SChristoph Hellwig  * but other filesystems need to take care of this on their own.
1098df2d6f26SChristoph Hellwig  *
1099df2d6f26SChristoph Hellwig  * NOTE: if you pass "sdio" to anything by pointer make sure that function
1100df2d6f26SChristoph Hellwig  * is always inlined. Otherwise gcc is unable to split the structure into
1101df2d6f26SChristoph Hellwig  * individual fields and will generate much worse code. This is important
1102df2d6f26SChristoph Hellwig  * for the whole file.
1103df2d6f26SChristoph Hellwig  */
__blockdev_direct_IO(struct kiocb * iocb,struct inode * inode,struct block_device * bdev,struct iov_iter * iter,get_block_t get_block,dio_iodone_t end_io,int flags)1104ba253fbfSAndi Kleen ssize_t __blockdev_direct_IO(struct kiocb *iocb, struct inode *inode,
1105ba253fbfSAndi Kleen 		struct block_device *bdev, struct iov_iter *iter,
1106ba253fbfSAndi Kleen 		get_block_t get_block, dio_iodone_t end_io,
1107ba253fbfSAndi Kleen 		int flags)
1108ba253fbfSAndi Kleen {
1109eafdc7d1SChristoph Hellwig 	unsigned i_blkbits = READ_ONCE(inode->i_blkbits);
1110c22198e7SChristoph Hellwig 	unsigned blkbits = i_blkbits;
111117f8c842SOmar Sandoval 	unsigned blocksize_mask = (1 << blkbits) - 1;
1112c8b8e32dSChristoph Hellwig 	ssize_t retval = -EINVAL;
11130aaf08deSAl Viro 	const size_t count = iov_iter_count(iter);
11141da177e4SLinus Torvalds 	loff_t offset = iocb->ki_pos;
11156aa7de05SMark Rutland 	const loff_t end = offset + count;
1116ab73857eSLinus Torvalds 	struct dio *dio;
11171da177e4SLinus Torvalds 	struct dio_submit sdio = { 0, };
11181da177e4SLinus Torvalds 	struct buffer_head map_bh = { 0, };
11191c0ff0f1SNikolay Borisov 	struct blk_plug plug;
1120c8b8e32dSChristoph Hellwig 	unsigned long align = offset | iov_iter_alignment(iter);
11211c0ff0f1SNikolay Borisov 
11221da177e4SLinus Torvalds 	/*
1123eb28be2bSAndi Kleen 	 * Avoid references to bdev if not absolutely needed to give
1124847cc637SAndi Kleen 	 * the early prefetch in the caller enough time.
1125647d1e4cSFengguang Wu 	 */
1126886a3911SAl Viro 
11271da177e4SLinus Torvalds 	/* watch out for a 0 len io from a tricksy fs */
112865dd2aa9SAndi Kleen 	if (iov_iter_rw(iter) == READ && !count)
112965dd2aa9SAndi Kleen 		return 0;
113065dd2aa9SAndi Kleen 
113165dd2aa9SAndi Kleen 	dio = kmem_cache_alloc(dio_cache, GFP_KERNEL);
11321da177e4SLinus Torvalds 	if (!dio)
1133f9b5570dSChristoph Hellwig 		return -ENOMEM;
11341c0ff0f1SNikolay Borisov 	/*
1135f9b5570dSChristoph Hellwig 	 * Believe it or not, zeroing out the page array caused a .5%
1136f9b5570dSChristoph Hellwig 	 * performance regression in a database benchmark.  So, we take
11376e8267f5SAndi Kleen 	 * care to only zero out what's needed.
11381da177e4SLinus Torvalds 	 */
113946d71602SGabriel Krisman Bertazi 	memset(dio, 0, offsetof(struct dio, pages));
114023aee091SJeff Moyer 
114123aee091SJeff Moyer 	dio->flags = flags;
114223aee091SJeff Moyer 	if (dio->flags & DIO_LOCKING && iov_iter_rw(iter) == READ) {
114323aee091SJeff Moyer 		/* will be released by direct_io_worker */
114423aee091SJeff Moyer 		inode_lock(inode);
114523aee091SJeff Moyer 	}
11461da177e4SLinus Torvalds 	dio->is_pinned = iov_iter_extract_will_pin(iter);
11475fe878aeSChristoph Hellwig 
11480a9164cbSGabriel Krisman Bertazi 	/* Once we sampled i_size check for reads beyond EOF */
11495fe878aeSChristoph Hellwig 	dio->i_size = i_size_read(inode);
11505955102cSAl Viro 	if (iov_iter_rw(iter) == READ && offset >= dio->i_size) {
1151df2d6f26SChristoph Hellwig 		retval = 0;
11521ccf164eSDavid Howells 		goto fail_dio;
11531da177e4SLinus Torvalds 	}
115474cedf9bSJan Kara 
115574cedf9bSJan Kara 	if (align & blocksize_mask) {
115674cedf9bSJan Kara 		if (bdev)
11572d4594acSAl Viro 			blkbits = blksize_bits(bdev_logical_block_size(bdev));
115846d71602SGabriel Krisman Bertazi 		blocksize_mask = (1 << blkbits) - 1;
115974cedf9bSJan Kara 		if (align & blocksize_mask)
116074cedf9bSJan Kara 			goto fail_dio;
116141b21af3SGabriel Krisman Bertazi 	}
116241b21af3SGabriel Krisman Bertazi 
116341b21af3SGabriel Krisman Bertazi 	if (dio->flags & DIO_LOCKING && iov_iter_rw(iter) == READ) {
116441b21af3SGabriel Krisman Bertazi 		struct address_space *mapping = iocb->ki_filp->f_mapping;
116541b21af3SGabriel Krisman Bertazi 
116641b21af3SGabriel Krisman Bertazi 		retval = filemap_write_and_wait_range(mapping, offset, end - 1);
116741b21af3SGabriel Krisman Bertazi 		if (retval)
116841b21af3SGabriel Krisman Bertazi 			goto fail_dio;
11690a9164cbSGabriel Krisman Bertazi 	}
11700a9164cbSGabriel Krisman Bertazi 
11710a9164cbSGabriel Krisman Bertazi 	/*
11720a9164cbSGabriel Krisman Bertazi 	 * For file extending writes updating i_size before data writeouts
11730a9164cbSGabriel Krisman Bertazi 	 * complete can expose uninitialized blocks in dumb filesystems.
11740a9164cbSGabriel Krisman Bertazi 	 * In that case we need to wait for I/O completion even if asked
11751da177e4SLinus Torvalds 	 * for an asynchronous write.
11761da177e4SLinus Torvalds 	 */
11775fe878aeSChristoph Hellwig 	if (is_sync_kiocb(iocb))
117860392573SChristoph Hellwig 		dio->is_async = false;
117960392573SChristoph Hellwig 	else if (iov_iter_rw(iter) == WRITE && end > i_size_read(inode))
118060392573SChristoph Hellwig 		dio->is_async = false;
118160392573SChristoph Hellwig 	else
11821da177e4SLinus Torvalds 		dio->is_async = true;
118360392573SChristoph Hellwig 
118460392573SChristoph Hellwig 	dio->inode = inode;
1185c8f4c36fSNikolay Borisov 	if (iov_iter_rw(iter) == WRITE) {
118660392573SChristoph Hellwig 		dio->opf = REQ_OP_WRITE | REQ_SYNC | REQ_IDLE;
118760392573SChristoph Hellwig 		if (iocb->ki_flags & IOCB_NOWAIT)
118860392573SChristoph Hellwig 			dio->opf |= REQ_NOWAIT;
118960392573SChristoph Hellwig 	} else {
1190847cc637SAndi Kleen 		dio->opf = REQ_OP_READ;
11918a4c1e42SMike Christie 	}
1192c6293eacSBart Van Assche 
119303a07c92SGoldwyn Rodrigues 	/*
1194c6293eacSBart Van Assche 	 * For AIO O_(D)SYNC writes we need to defer completions to a workqueue
11958a4c1e42SMike Christie 	 * so that we can call ->fsync.
1196c6293eacSBart Van Assche 	 */
11978a4c1e42SMike Christie 	if (dio->is_async && iov_iter_rw(iter) == WRITE) {
119802afc27fSChristoph Hellwig 		retval = 0;
119902afc27fSChristoph Hellwig 		if (iocb_is_dsync(iocb))
120002afc27fSChristoph Hellwig 			retval = dio_set_defer_completion(dio);
120102afc27fSChristoph Hellwig 		else if (!dio->inode->i_sb->s_dio_done_wq) {
120202afc27fSChristoph Hellwig 			/*
1203332391a9SLukas Czerner 			 * In case of AIO write racing with buffered read we
1204332391a9SLukas Czerner 			 * need to defer completion. We can't decide this now,
120591b94c5dSAl Viro 			 * however the workqueue needs to be initialized here.
120602afc27fSChristoph Hellwig 			 */
1207332391a9SLukas Czerner 			retval = sb_init_dio_done_wq(dio->inode->i_sb);
1208332391a9SLukas Czerner 		}
1209332391a9SLukas Czerner 		if (retval)
1210332391a9SLukas Czerner 			goto fail_dio;
1211332391a9SLukas Czerner 	}
1212332391a9SLukas Czerner 
1213332391a9SLukas Czerner 	/*
1214332391a9SLukas Czerner 	 * Will be decremented at I/O completion time.
121546d71602SGabriel Krisman Bertazi 	 */
121646d71602SGabriel Krisman Bertazi 	inode_dio_begin(inode);
121702afc27fSChristoph Hellwig 
121802afc27fSChristoph Hellwig 	retval = 0;
121902afc27fSChristoph Hellwig 	sdio.blkbits = blkbits;
122002afc27fSChristoph Hellwig 	sdio.blkfactor = i_blkbits - blkbits;
122102afc27fSChristoph Hellwig 	sdio.block_in_file = offset >> blkbits;
1222fe0f07d0SJens Axboe 
122302afc27fSChristoph Hellwig 	sdio.get_block = get_block;
122402afc27fSChristoph Hellwig 	dio->end_io = end_io;
1225847cc637SAndi Kleen 	sdio.final_block_in_bio = -1;
1226ab73857eSLinus Torvalds 	sdio.next_block_for_io = -1;
1227847cc637SAndi Kleen 
1228847cc637SAndi Kleen 	dio->iocb = iocb;
1229847cc637SAndi Kleen 
1230847cc637SAndi Kleen 	spin_lock_init(&dio->bio_lock);
1231847cc637SAndi Kleen 	dio->refcount = 1;
1232847cc637SAndi Kleen 
1233847cc637SAndi Kleen 	dio->should_dirty = user_backed_iter(iter) && iov_iter_rw(iter) == READ;
1234847cc637SAndi Kleen 	sdio.iter = iter;
1235847cc637SAndi Kleen 	sdio.final_block_in_request = end >> blkbits;
1236847cc637SAndi Kleen 
1237847cc637SAndi Kleen 	/*
1238847cc637SAndi Kleen 	 * In case of non-aligned buffers, we may need 2 more
1239fcb14cb1SAl Viro 	 * pages since we need to zero out first and last block.
12407b2c99d1SAl Viro 	 */
12411c0ff0f1SNikolay Borisov 	if (unlikely(sdio.blkfactor))
12427b2c99d1SAl Viro 		sdio.pages_in_io = 2;
1243847cc637SAndi Kleen 
1244847cc637SAndi Kleen 	sdio.pages_in_io += iov_iter_npages(iter, INT_MAX);
1245847cc637SAndi Kleen 
1246847cc637SAndi Kleen 	blk_start_plug(&plug);
1247847cc637SAndi Kleen 
1248847cc637SAndi Kleen 	retval = do_direct_IO(dio, &sdio, &map_bh);
1249847cc637SAndi Kleen 	if (retval)
1250f67da30cSAl Viro 		dio_cleanup(dio, &sdio);
1251847cc637SAndi Kleen 
1252647d1e4cSFengguang Wu 	if (retval == -ENOTBLK) {
1253647d1e4cSFengguang Wu 		/*
1254847cc637SAndi Kleen 		 * The remaining part of the request will be
12557b2c99d1SAl Viro 		 * handled by buffered I/O when we return
1256847cc637SAndi Kleen 		 */
1257847cc637SAndi Kleen 		retval = 0;
1258847cc637SAndi Kleen 	}
1259847cc637SAndi Kleen 	/*
1260847cc637SAndi Kleen 	 * There may be some unwritten disk at the end of a part-written
12613d742d4bSRandy Dunlap 	 * fs-block-sized block.  Go zero that now.
1262847cc637SAndi Kleen 	 */
1263847cc637SAndi Kleen 	dio_zero_block(dio, &sdio, 1, &map_bh);
1264847cc637SAndi Kleen 
1265847cc637SAndi Kleen 	if (sdio.cur_page) {
1266847cc637SAndi Kleen 		ssize_t ret2;
1267847cc637SAndi Kleen 
1268847cc637SAndi Kleen 		ret2 = dio_send_cur_page(dio, &sdio, &map_bh);
1269847cc637SAndi Kleen 		if (retval == 0)
1270847cc637SAndi Kleen 			retval = ret2;
1271847cc637SAndi Kleen 		dio_unpin_page(dio, sdio.cur_page);
1272847cc637SAndi Kleen 		sdio.cur_page = NULL;
1273847cc637SAndi Kleen 	}
1274847cc637SAndi Kleen 	if (sdio.bio)
1275847cc637SAndi Kleen 		dio_bio_submit(dio, &sdio);
1276847cc637SAndi Kleen 
12771ccf164eSDavid Howells 	blk_finish_plug(&plug);
1278847cc637SAndi Kleen 
1279847cc637SAndi Kleen 	/*
1280847cc637SAndi Kleen 	 * It is possible that, we return short IO due to end of file.
1281847cc637SAndi Kleen 	 * In that case, we need to release all the pages we got hold on.
1282847cc637SAndi Kleen 	 */
1283647d1e4cSFengguang Wu 	dio_cleanup(dio, &sdio);
1284647d1e4cSFengguang Wu 
1285847cc637SAndi Kleen 	/*
1286847cc637SAndi Kleen 	 * All block lookups have been performed. For READ requests
1287847cc637SAndi Kleen 	 * we can let i_mutex go now that its achieved its purpose
1288847cc637SAndi Kleen 	 * of protecting us from looking up uninitialized blocks.
1289847cc637SAndi Kleen 	 */
1290847cc637SAndi Kleen 	if (iov_iter_rw(iter) == READ && (dio->flags & DIO_LOCKING))
1291847cc637SAndi Kleen 		inode_unlock(dio->inode);
1292847cc637SAndi Kleen 
1293847cc637SAndi Kleen 	/*
1294847cc637SAndi Kleen 	 * The only time we want to leave bios in flight is when a successful
1295847cc637SAndi Kleen 	 * partial aio read or full aio write have been setup.  In that case
129617f8c842SOmar Sandoval 	 * bio completion will call aio_complete.  The only time it's safe to
12975955102cSAl Viro 	 * call aio_complete is when we return -EIOCBQUEUED, so we key on that.
1298847cc637SAndi Kleen 	 * This had *better* be the only place that raises -EIOCBQUEUED.
1299847cc637SAndi Kleen 	 */
1300847cc637SAndi Kleen 	BUG_ON(retval == -EIOCBQUEUED);
1301847cc637SAndi Kleen 	if (dio->is_async && retval == 0 && dio->result &&
1302847cc637SAndi Kleen 	    (iov_iter_rw(iter) == READ || dio->result == count))
1303847cc637SAndi Kleen 		retval = -EIOCBQUEUED;
1304847cc637SAndi Kleen 	else
1305847cc637SAndi Kleen 		dio_await_completion(dio);
1306847cc637SAndi Kleen 
1307847cc637SAndi Kleen 	if (drop_refcount(dio) == 0) {
130817f8c842SOmar Sandoval 		retval = dio_complete(dio, retval, DIO_COMPLETE_INVALIDATE);
1309847cc637SAndi Kleen 	} else
1310af436472SChristoph Hellwig 		BUG_ON(retval != -EIOCBQUEUED);
1311847cc637SAndi Kleen 
1312847cc637SAndi Kleen 	return retval;
1313847cc637SAndi Kleen 
1314ffe51f01SLukas Czerner fail_dio:
1315847cc637SAndi Kleen 	if (dio->flags & DIO_LOCKING && iov_iter_rw(iter) == READ)
1316847cc637SAndi Kleen 		inode_unlock(inode);
13171da177e4SLinus Torvalds 
131846d71602SGabriel Krisman Bertazi 	kmem_cache_free(dio_cache, dio);
131946d71602SGabriel Krisman Bertazi 	return retval;
132046d71602SGabriel Krisman Bertazi }
132146d71602SGabriel Krisman Bertazi EXPORT_SYMBOL(__blockdev_direct_IO);
132246d71602SGabriel Krisman Bertazi 
dio_init(void)132346d71602SGabriel Krisman Bertazi static __init int dio_init(void)
132446d71602SGabriel Krisman Bertazi {
13257bb46a67Snpiggin@suse.de 	dio_cache = KMEM_CACHE(dio, SLAB_PANIC);
13267bb46a67Snpiggin@suse.de 	return 0;
13271da177e4SLinus Torvalds }
13286e8267f5SAndi Kleen module_init(dio_init)
13296e8267f5SAndi Kleen