• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * fs/direct-io.c
4  *
5  * Copyright (C) 2002, Linus Torvalds.
6  *
7  * O_DIRECT
8  *
9  * 04Jul2002	Andrew Morton
10  *		Initial version
11  * 11Sep2002	janetinc@us.ibm.com
12  * 		added readv/writev support.
13  * 29Oct2002	Andrew Morton
14  *		rewrote bio_add_page() support.
15  * 30Oct2002	pbadari@us.ibm.com
16  *		added support for non-aligned IO.
17  * 06Nov2002	pbadari@us.ibm.com
18  *		added asynchronous IO support.
19  * 21Jul2003	nathans@sgi.com
20  *		added IO completion notifier.
21  */
22 
23 #include <linux/kernel.h>
24 #include <linux/module.h>
25 #include <linux/types.h>
26 #include <linux/fs.h>
27 #include <linux/fscrypt.h>
28 #include <linux/mm.h>
29 #include <linux/slab.h>
30 #include <linux/highmem.h>
31 #include <linux/pagemap.h>
32 #include <linux/task_io_accounting_ops.h>
33 #include <linux/bio.h>
34 #include <linux/wait.h>
35 #include <linux/err.h>
36 #include <linux/blkdev.h>
37 #include <linux/buffer_head.h>
38 #include <linux/rwsem.h>
39 #include <linux/uio.h>
40 #include <linux/atomic.h>
41 #include <linux/prefetch.h>
42 
43 /*
44  * How many user pages to map in one call to get_user_pages().  This determines
45  * the size of a structure in the slab cache
46  */
47 #define DIO_PAGES	64
48 
49 /*
50  * Flags for dio_complete()
51  */
52 #define DIO_COMPLETE_ASYNC		0x01	/* This is async IO */
53 #define DIO_COMPLETE_INVALIDATE		0x02	/* Can invalidate pages */
54 
55 /*
56  * This code generally works in units of "dio_blocks".  A dio_block is
57  * somewhere between the hard sector size and the filesystem block size.  it
58  * is determined on a per-invocation basis.   When talking to the filesystem
59  * we need to convert dio_blocks to fs_blocks by scaling the dio_block quantity
60  * down by dio->blkfactor.  Similarly, fs-blocksize quantities are converted
61  * to bio_block quantities by shifting left by blkfactor.
62  *
63  * If blkfactor is zero then the user's request was aligned to the filesystem's
64  * blocksize.
65  */
66 
67 /* dio_state only used in the submission path */
68 
69 struct dio_submit {
70 	struct bio *bio;		/* bio under assembly */
71 	unsigned blkbits;		/* doesn't change */
72 	unsigned blkfactor;		/* When we're using an alignment which
73 					   is finer than the filesystem's soft
74 					   blocksize, this specifies how much
75 					   finer.  blkfactor=2 means 1/4-block
76 					   alignment.  Does not change */
77 	unsigned start_zero_done;	/* flag: sub-blocksize zeroing has
78 					   been performed at the start of a
79 					   write */
80 	int pages_in_io;		/* approximate total IO pages */
81 	sector_t block_in_file;		/* Current offset into the underlying
82 					   file in dio_block units. */
83 	unsigned blocks_available;	/* At block_in_file.  changes */
84 	int reap_counter;		/* rate limit reaping */
85 	sector_t final_block_in_request;/* doesn't change */
86 	int boundary;			/* prev block is at a boundary */
87 	get_block_t *get_block;		/* block mapping function */
88 	dio_submit_t *submit_io;	/* IO submition function */
89 
90 	loff_t logical_offset_in_bio;	/* current first logical block in bio */
91 	sector_t final_block_in_bio;	/* current final block in bio + 1 */
92 	sector_t next_block_for_io;	/* next block to be put under IO,
93 					   in dio_blocks units */
94 
95 	/*
96 	 * Deferred addition of a page to the dio.  These variables are
97 	 * private to dio_send_cur_page(), submit_page_section() and
98 	 * dio_bio_add_page().
99 	 */
100 	struct page *cur_page;		/* The page */
101 	unsigned cur_page_offset;	/* Offset into it, in bytes */
102 	unsigned cur_page_len;		/* Nr of bytes at cur_page_offset */
103 	sector_t cur_page_block;	/* Where it starts */
104 	loff_t cur_page_fs_offset;	/* Offset in file */
105 
106 	struct iov_iter *iter;
107 	/*
108 	 * Page queue.  These variables belong to dio_refill_pages() and
109 	 * dio_get_page().
110 	 */
111 	unsigned head;			/* next page to process */
112 	unsigned tail;			/* last valid page + 1 */
113 	size_t from, to;
114 };
115 
116 /* dio_state communicated between submission path and end_io */
117 struct dio {
118 	int flags;			/* doesn't change */
119 	int op;
120 	int op_flags;
121 	blk_qc_t bio_cookie;
122 	struct gendisk *bio_disk;
123 	struct inode *inode;
124 	loff_t i_size;			/* i_size when submitted */
125 	dio_iodone_t *end_io;		/* IO completion function */
126 
127 	void *private;			/* copy from map_bh.b_private */
128 
129 	/* BIO completion state */
130 	spinlock_t bio_lock;		/* protects BIO fields below */
131 	int page_errors;		/* errno from get_user_pages() */
132 	int is_async;			/* is IO async ? */
133 	bool defer_completion;		/* defer AIO completion to workqueue? */
134 	bool should_dirty;		/* if pages should be dirtied */
135 	int io_error;			/* IO error in completion path */
136 	unsigned long refcount;		/* direct_io_worker() and bios */
137 	struct bio *bio_list;		/* singly linked via bi_private */
138 	struct task_struct *waiter;	/* waiting task (NULL if none) */
139 
140 	/* AIO related stuff */
141 	struct kiocb *iocb;		/* kiocb */
142 	ssize_t result;                 /* IO result */
143 
144 	/*
145 	 * pages[] (and any fields placed after it) are not zeroed out at
146 	 * allocation time.  Don't add new fields after pages[] unless you
147 	 * wish that they not be zeroed.
148 	 */
149 	union {
150 		struct page *pages[DIO_PAGES];	/* page buffer */
151 		struct work_struct complete_work;/* deferred AIO completion */
152 	};
153 } ____cacheline_aligned_in_smp;
154 
155 static struct kmem_cache *dio_cache __read_mostly;
156 
157 /*
158  * How many pages are in the queue?
159  */
dio_pages_present(struct dio_submit * sdio)160 static inline unsigned dio_pages_present(struct dio_submit *sdio)
161 {
162 	return sdio->tail - sdio->head;
163 }
164 
165 /*
166  * Go grab and pin some userspace pages.   Typically we'll get 64 at a time.
167  */
dio_refill_pages(struct dio * dio,struct dio_submit * sdio)168 static inline int dio_refill_pages(struct dio *dio, struct dio_submit *sdio)
169 {
170 	ssize_t ret;
171 
172 	ret = iov_iter_get_pages(sdio->iter, dio->pages, LONG_MAX, DIO_PAGES,
173 				&sdio->from);
174 
175 	if (ret < 0 && sdio->blocks_available && (dio->op == REQ_OP_WRITE)) {
176 		struct page *page = ZERO_PAGE(0);
177 		/*
178 		 * A memory fault, but the filesystem has some outstanding
179 		 * mapped blocks.  We need to use those blocks up to avoid
180 		 * leaking stale data in the file.
181 		 */
182 		if (dio->page_errors == 0)
183 			dio->page_errors = ret;
184 		get_page(page);
185 		dio->pages[0] = page;
186 		sdio->head = 0;
187 		sdio->tail = 1;
188 		sdio->from = 0;
189 		sdio->to = PAGE_SIZE;
190 		return 0;
191 	}
192 
193 	if (ret >= 0) {
194 		iov_iter_advance(sdio->iter, ret);
195 		ret += sdio->from;
196 		sdio->head = 0;
197 		sdio->tail = (ret + PAGE_SIZE - 1) / PAGE_SIZE;
198 		sdio->to = ((ret - 1) & (PAGE_SIZE - 1)) + 1;
199 		return 0;
200 	}
201 	return ret;
202 }
203 
204 /*
205  * Get another userspace page.  Returns an ERR_PTR on error.  Pages are
206  * buffered inside the dio so that we can call get_user_pages() against a
207  * decent number of pages, less frequently.  To provide nicer use of the
208  * L1 cache.
209  */
dio_get_page(struct dio * dio,struct dio_submit * sdio)210 static inline struct page *dio_get_page(struct dio *dio,
211 					struct dio_submit *sdio)
212 {
213 	if (dio_pages_present(sdio) == 0) {
214 		int ret;
215 
216 		ret = dio_refill_pages(dio, sdio);
217 		if (ret)
218 			return ERR_PTR(ret);
219 		BUG_ON(dio_pages_present(sdio) == 0);
220 	}
221 	return dio->pages[sdio->head];
222 }
223 
224 /*
225  * Warn about a page cache invalidation failure during a direct io write.
226  */
dio_warn_stale_pagecache(struct file * filp)227 void dio_warn_stale_pagecache(struct file *filp)
228 {
229 	static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
230 	char pathname[128];
231 	struct inode *inode = file_inode(filp);
232 	char *path;
233 
234 	errseq_set(&inode->i_mapping->wb_err, -EIO);
235 	if (__ratelimit(&_rs)) {
236 		path = file_path(filp, pathname, sizeof(pathname));
237 		if (IS_ERR(path))
238 			path = "(unknown)";
239 		pr_crit("Page cache invalidation failure on direct I/O.  Possible data corruption due to collision with buffered I/O!\n");
240 		pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
241 			current->comm);
242 	}
243 }
244 
245 /*
246  * dio_complete() - called when all DIO BIO I/O has been completed
247  *
248  * This drops i_dio_count, lets interested parties know that a DIO operation
249  * has completed, and calculates the resulting return code for the operation.
250  *
251  * It lets the filesystem know if it registered an interest earlier via
252  * get_block.  Pass the private field of the map buffer_head so that
253  * filesystems can use it to hold additional state between get_block calls and
254  * dio_complete.
255  */
dio_complete(struct dio * dio,ssize_t ret,unsigned int flags)256 static ssize_t dio_complete(struct dio *dio, ssize_t ret, unsigned int flags)
257 {
258 	loff_t offset = dio->iocb->ki_pos;
259 	ssize_t transferred = 0;
260 	int err;
261 
262 	/*
263 	 * AIO submission can race with bio completion to get here while
264 	 * expecting to have the last io completed by bio completion.
265 	 * In that case -EIOCBQUEUED is in fact not an error we want
266 	 * to preserve through this call.
267 	 */
268 	if (ret == -EIOCBQUEUED)
269 		ret = 0;
270 
271 	if (dio->result) {
272 		transferred = dio->result;
273 
274 		/* Check for short read case */
275 		if ((dio->op == REQ_OP_READ) &&
276 		    ((offset + transferred) > dio->i_size))
277 			transferred = dio->i_size - offset;
278 		/* ignore EFAULT if some IO has been done */
279 		if (unlikely(ret == -EFAULT) && transferred)
280 			ret = 0;
281 	}
282 
283 	if (ret == 0)
284 		ret = dio->page_errors;
285 	if (ret == 0)
286 		ret = dio->io_error;
287 	if (ret == 0)
288 		ret = transferred;
289 
290 	if (dio->end_io) {
291 		// XXX: ki_pos??
292 		err = dio->end_io(dio->iocb, offset, ret, dio->private);
293 		if (err)
294 			ret = err;
295 	}
296 
297 	/*
298 	 * Try again to invalidate clean pages which might have been cached by
299 	 * non-direct readahead, or faulted in by get_user_pages() if the source
300 	 * of the write was an mmap'ed region of the file we're writing.  Either
301 	 * one is a pretty crazy thing to do, so we don't support it 100%.  If
302 	 * this invalidation fails, tough, the write still worked...
303 	 *
304 	 * And this page cache invalidation has to be after dio->end_io(), as
305 	 * some filesystems convert unwritten extents to real allocations in
306 	 * end_io() when necessary, otherwise a racing buffer read would cache
307 	 * zeros from unwritten extents.
308 	 */
309 	if (flags & DIO_COMPLETE_INVALIDATE &&
310 	    ret > 0 && dio->op == REQ_OP_WRITE &&
311 	    dio->inode->i_mapping->nrpages) {
312 		err = invalidate_inode_pages2_range(dio->inode->i_mapping,
313 					offset >> PAGE_SHIFT,
314 					(offset + ret - 1) >> PAGE_SHIFT);
315 		if (err)
316 			dio_warn_stale_pagecache(dio->iocb->ki_filp);
317 	}
318 
319 	inode_dio_end(dio->inode);
320 
321 	if (flags & DIO_COMPLETE_ASYNC) {
322 		/*
323 		 * generic_write_sync expects ki_pos to have been updated
324 		 * already, but the submission path only does this for
325 		 * synchronous I/O.
326 		 */
327 		dio->iocb->ki_pos += transferred;
328 
329 		if (ret > 0 && dio->op == REQ_OP_WRITE)
330 			ret = generic_write_sync(dio->iocb, ret);
331 		dio->iocb->ki_complete(dio->iocb, ret, 0);
332 	}
333 
334 	kmem_cache_free(dio_cache, dio);
335 	return ret;
336 }
337 
dio_aio_complete_work(struct work_struct * work)338 static void dio_aio_complete_work(struct work_struct *work)
339 {
340 	struct dio *dio = container_of(work, struct dio, complete_work);
341 
342 	dio_complete(dio, 0, DIO_COMPLETE_ASYNC | DIO_COMPLETE_INVALIDATE);
343 }
344 
345 static blk_status_t dio_bio_complete(struct dio *dio, struct bio *bio);
346 
347 /*
348  * Asynchronous IO callback.
349  */
dio_bio_end_aio(struct bio * bio)350 static void dio_bio_end_aio(struct bio *bio)
351 {
352 	struct dio *dio = bio->bi_private;
353 	unsigned long remaining;
354 	unsigned long flags;
355 	bool defer_completion = false;
356 
357 	/* cleanup the bio */
358 	dio_bio_complete(dio, bio);
359 
360 	spin_lock_irqsave(&dio->bio_lock, flags);
361 	remaining = --dio->refcount;
362 	if (remaining == 1 && dio->waiter)
363 		wake_up_process(dio->waiter);
364 	spin_unlock_irqrestore(&dio->bio_lock, flags);
365 
366 	if (remaining == 0) {
367 		/*
368 		 * Defer completion when defer_completion is set or
369 		 * when the inode has pages mapped and this is AIO write.
370 		 * We need to invalidate those pages because there is a
371 		 * chance they contain stale data in the case buffered IO
372 		 * went in between AIO submission and completion into the
373 		 * same region.
374 		 */
375 		if (dio->result)
376 			defer_completion = dio->defer_completion ||
377 					   (dio->op == REQ_OP_WRITE &&
378 					    dio->inode->i_mapping->nrpages);
379 		if (defer_completion) {
380 			INIT_WORK(&dio->complete_work, dio_aio_complete_work);
381 			queue_work(dio->inode->i_sb->s_dio_done_wq,
382 				   &dio->complete_work);
383 		} else {
384 			dio_complete(dio, 0, DIO_COMPLETE_ASYNC);
385 		}
386 	}
387 }
388 
389 /*
390  * The BIO completion handler simply queues the BIO up for the process-context
391  * handler.
392  *
393  * During I/O bi_private points at the dio.  After I/O, bi_private is used to
394  * implement a singly-linked list of completed BIOs, at dio->bio_list.
395  */
dio_bio_end_io(struct bio * bio)396 static void dio_bio_end_io(struct bio *bio)
397 {
398 	struct dio *dio = bio->bi_private;
399 	unsigned long flags;
400 
401 	spin_lock_irqsave(&dio->bio_lock, flags);
402 	bio->bi_private = dio->bio_list;
403 	dio->bio_list = bio;
404 	if (--dio->refcount == 1 && dio->waiter)
405 		wake_up_process(dio->waiter);
406 	spin_unlock_irqrestore(&dio->bio_lock, flags);
407 }
408 
409 /**
410  * dio_end_io - handle the end io action for the given bio
411  * @bio: The direct io bio thats being completed
412  *
413  * This is meant to be called by any filesystem that uses their own dio_submit_t
414  * so that the DIO specific endio actions are dealt with after the filesystem
415  * has done it's completion work.
416  */
dio_end_io(struct bio * bio)417 void dio_end_io(struct bio *bio)
418 {
419 	struct dio *dio = bio->bi_private;
420 
421 	if (dio->is_async)
422 		dio_bio_end_aio(bio);
423 	else
424 		dio_bio_end_io(bio);
425 }
426 EXPORT_SYMBOL_GPL(dio_end_io);
427 
428 static inline void
dio_bio_alloc(struct dio * dio,struct dio_submit * sdio,struct block_device * bdev,sector_t first_sector,int nr_vecs)429 dio_bio_alloc(struct dio *dio, struct dio_submit *sdio,
430 	      struct block_device *bdev,
431 	      sector_t first_sector, int nr_vecs)
432 {
433 	struct bio *bio;
434 	struct inode *inode = dio->inode;
435 
436 	/*
437 	 * bio_alloc() is guaranteed to return a bio when allowed to sleep and
438 	 * we request a valid number of vectors.
439 	 */
440 	bio = bio_alloc(GFP_KERNEL, nr_vecs);
441 
442 	fscrypt_set_bio_crypt_ctx(bio, inode,
443 				  sdio->cur_page_fs_offset >> inode->i_blkbits,
444 				  GFP_KERNEL);
445 	bio_set_dev(bio, bdev);
446 	bio->bi_iter.bi_sector = first_sector;
447 	bio_set_op_attrs(bio, dio->op, dio->op_flags);
448 	if (dio->is_async)
449 		bio->bi_end_io = dio_bio_end_aio;
450 	else
451 		bio->bi_end_io = dio_bio_end_io;
452 
453 	bio->bi_write_hint = dio->iocb->ki_hint;
454 
455 	sdio->bio = bio;
456 	sdio->logical_offset_in_bio = sdio->cur_page_fs_offset;
457 }
458 
459 /*
460  * In the AIO read case we speculatively dirty the pages before starting IO.
461  * During IO completion, any of these pages which happen to have been written
462  * back will be redirtied by bio_check_pages_dirty().
463  *
464  * bios hold a dio reference between submit_bio and ->end_io.
465  */
dio_bio_submit(struct dio * dio,struct dio_submit * sdio)466 static inline void dio_bio_submit(struct dio *dio, struct dio_submit *sdio)
467 {
468 	struct bio *bio = sdio->bio;
469 	unsigned long flags;
470 
471 	bio->bi_private = dio;
472 
473 	spin_lock_irqsave(&dio->bio_lock, flags);
474 	dio->refcount++;
475 	spin_unlock_irqrestore(&dio->bio_lock, flags);
476 
477 	if (dio->is_async && dio->op == REQ_OP_READ && dio->should_dirty)
478 		bio_set_pages_dirty(bio);
479 
480 	dio->bio_disk = bio->bi_disk;
481 
482 	if (sdio->submit_io) {
483 		sdio->submit_io(bio, dio->inode, sdio->logical_offset_in_bio);
484 		dio->bio_cookie = BLK_QC_T_NONE;
485 	} else
486 		dio->bio_cookie = submit_bio(bio);
487 
488 	sdio->bio = NULL;
489 	sdio->boundary = 0;
490 	sdio->logical_offset_in_bio = 0;
491 }
492 
493 /*
494  * Release any resources in case of a failure
495  */
dio_cleanup(struct dio * dio,struct dio_submit * sdio)496 static inline void dio_cleanup(struct dio *dio, struct dio_submit *sdio)
497 {
498 	while (sdio->head < sdio->tail)
499 		put_page(dio->pages[sdio->head++]);
500 }
501 
502 /*
503  * Wait for the next BIO to complete.  Remove it and return it.  NULL is
504  * returned once all BIOs have been completed.  This must only be called once
505  * all bios have been issued so that dio->refcount can only decrease.  This
506  * requires that that the caller hold a reference on the dio.
507  */
dio_await_one(struct dio * dio)508 static struct bio *dio_await_one(struct dio *dio)
509 {
510 	unsigned long flags;
511 	struct bio *bio = NULL;
512 
513 	spin_lock_irqsave(&dio->bio_lock, flags);
514 
515 	/*
516 	 * Wait as long as the list is empty and there are bios in flight.  bio
517 	 * completion drops the count, maybe adds to the list, and wakes while
518 	 * holding the bio_lock so we don't need set_current_state()'s barrier
519 	 * and can call it after testing our condition.
520 	 */
521 	while (dio->refcount > 1 && dio->bio_list == NULL) {
522 		__set_current_state(TASK_UNINTERRUPTIBLE);
523 		dio->waiter = current;
524 		spin_unlock_irqrestore(&dio->bio_lock, flags);
525 		if (!(dio->iocb->ki_flags & IOCB_HIPRI) ||
526 		    !blk_poll(dio->bio_disk->queue, dio->bio_cookie, true))
527 			io_schedule();
528 		/* wake up sets us TASK_RUNNING */
529 		spin_lock_irqsave(&dio->bio_lock, flags);
530 		dio->waiter = NULL;
531 	}
532 	if (dio->bio_list) {
533 		bio = dio->bio_list;
534 		dio->bio_list = bio->bi_private;
535 	}
536 	spin_unlock_irqrestore(&dio->bio_lock, flags);
537 	return bio;
538 }
539 
540 /*
541  * Process one completed BIO.  No locks are held.
542  */
dio_bio_complete(struct dio * dio,struct bio * bio)543 static blk_status_t dio_bio_complete(struct dio *dio, struct bio *bio)
544 {
545 	blk_status_t err = bio->bi_status;
546 	bool should_dirty = dio->op == REQ_OP_READ && dio->should_dirty;
547 
548 	if (err) {
549 		if (err == BLK_STS_AGAIN && (bio->bi_opf & REQ_NOWAIT))
550 			dio->io_error = -EAGAIN;
551 		else
552 			dio->io_error = -EIO;
553 	}
554 
555 	if (dio->is_async && should_dirty) {
556 		bio_check_pages_dirty(bio);	/* transfers ownership */
557 	} else {
558 		bio_release_pages(bio, should_dirty);
559 		bio_put(bio);
560 	}
561 	return err;
562 }
563 
564 /*
565  * Wait on and process all in-flight BIOs.  This must only be called once
566  * all bios have been issued so that the refcount can only decrease.
567  * This just waits for all bios to make it through dio_bio_complete.  IO
568  * errors are propagated through dio->io_error and should be propagated via
569  * dio_complete().
570  */
dio_await_completion(struct dio * dio)571 static void dio_await_completion(struct dio *dio)
572 {
573 	struct bio *bio;
574 	do {
575 		bio = dio_await_one(dio);
576 		if (bio)
577 			dio_bio_complete(dio, bio);
578 	} while (bio);
579 }
580 
581 /*
582  * A really large O_DIRECT read or write can generate a lot of BIOs.  So
583  * to keep the memory consumption sane we periodically reap any completed BIOs
584  * during the BIO generation phase.
585  *
586  * This also helps to limit the peak amount of pinned userspace memory.
587  */
dio_bio_reap(struct dio * dio,struct dio_submit * sdio)588 static inline int dio_bio_reap(struct dio *dio, struct dio_submit *sdio)
589 {
590 	int ret = 0;
591 
592 	if (sdio->reap_counter++ >= 64) {
593 		while (dio->bio_list) {
594 			unsigned long flags;
595 			struct bio *bio;
596 			int ret2;
597 
598 			spin_lock_irqsave(&dio->bio_lock, flags);
599 			bio = dio->bio_list;
600 			dio->bio_list = bio->bi_private;
601 			spin_unlock_irqrestore(&dio->bio_lock, flags);
602 			ret2 = blk_status_to_errno(dio_bio_complete(dio, bio));
603 			if (ret == 0)
604 				ret = ret2;
605 		}
606 		sdio->reap_counter = 0;
607 	}
608 	return ret;
609 }
610 
611 /*
612  * Create workqueue for deferred direct IO completions. We allocate the
613  * workqueue when it's first needed. This avoids creating workqueue for
614  * filesystems that don't need it and also allows us to create the workqueue
615  * late enough so the we can include s_id in the name of the workqueue.
616  */
sb_init_dio_done_wq(struct super_block * sb)617 int sb_init_dio_done_wq(struct super_block *sb)
618 {
619 	struct workqueue_struct *old;
620 	struct workqueue_struct *wq = alloc_workqueue("dio/%s",
621 						      WQ_MEM_RECLAIM, 0,
622 						      sb->s_id);
623 	if (!wq)
624 		return -ENOMEM;
625 	/*
626 	 * This has to be atomic as more DIOs can race to create the workqueue
627 	 */
628 	old = cmpxchg(&sb->s_dio_done_wq, NULL, wq);
629 	/* Someone created workqueue before us? Free ours... */
630 	if (old)
631 		destroy_workqueue(wq);
632 	return 0;
633 }
634 
dio_set_defer_completion(struct dio * dio)635 static int dio_set_defer_completion(struct dio *dio)
636 {
637 	struct super_block *sb = dio->inode->i_sb;
638 
639 	if (dio->defer_completion)
640 		return 0;
641 	dio->defer_completion = true;
642 	if (!sb->s_dio_done_wq)
643 		return sb_init_dio_done_wq(sb);
644 	return 0;
645 }
646 
647 /*
648  * Call into the fs to map some more disk blocks.  We record the current number
649  * of available blocks at sdio->blocks_available.  These are in units of the
650  * fs blocksize, i_blocksize(inode).
651  *
652  * The fs is allowed to map lots of blocks at once.  If it wants to do that,
653  * it uses the passed inode-relative block number as the file offset, as usual.
654  *
655  * get_block() is passed the number of i_blkbits-sized blocks which direct_io
656  * has remaining to do.  The fs should not map more than this number of blocks.
657  *
658  * If the fs has mapped a lot of blocks, it should populate bh->b_size to
659  * indicate how much contiguous disk space has been made available at
660  * bh->b_blocknr.
661  *
662  * If *any* of the mapped blocks are new, then the fs must set buffer_new().
663  * This isn't very efficient...
664  *
665  * In the case of filesystem holes: the fs may return an arbitrarily-large
666  * hole by returning an appropriate value in b_size and by clearing
667  * buffer_mapped().  However the direct-io code will only process holes one
668  * block at a time - it will repeatedly call get_block() as it walks the hole.
669  */
get_more_blocks(struct dio * dio,struct dio_submit * sdio,struct buffer_head * map_bh)670 static int get_more_blocks(struct dio *dio, struct dio_submit *sdio,
671 			   struct buffer_head *map_bh)
672 {
673 	int ret;
674 	sector_t fs_startblk;	/* Into file, in filesystem-sized blocks */
675 	sector_t fs_endblk;	/* Into file, in filesystem-sized blocks */
676 	unsigned long fs_count;	/* Number of filesystem-sized blocks */
677 	int create;
678 	unsigned int i_blkbits = sdio->blkbits + sdio->blkfactor;
679 	loff_t i_size;
680 
681 	/*
682 	 * If there was a memory error and we've overwritten all the
683 	 * mapped blocks then we can now return that memory error
684 	 */
685 	ret = dio->page_errors;
686 	if (ret == 0) {
687 		BUG_ON(sdio->block_in_file >= sdio->final_block_in_request);
688 		fs_startblk = sdio->block_in_file >> sdio->blkfactor;
689 		fs_endblk = (sdio->final_block_in_request - 1) >>
690 					sdio->blkfactor;
691 		fs_count = fs_endblk - fs_startblk + 1;
692 
693 		map_bh->b_state = 0;
694 		map_bh->b_size = fs_count << i_blkbits;
695 
696 		/*
697 		 * For writes that could fill holes inside i_size on a
698 		 * DIO_SKIP_HOLES filesystem we forbid block creations: only
699 		 * overwrites are permitted. We will return early to the caller
700 		 * once we see an unmapped buffer head returned, and the caller
701 		 * will fall back to buffered I/O.
702 		 *
703 		 * Otherwise the decision is left to the get_blocks method,
704 		 * which may decide to handle it or also return an unmapped
705 		 * buffer head.
706 		 */
707 		create = dio->op == REQ_OP_WRITE;
708 		if (dio->flags & DIO_SKIP_HOLES) {
709 			i_size = i_size_read(dio->inode);
710 			if (i_size && fs_startblk <= (i_size - 1) >> i_blkbits)
711 				create = 0;
712 		}
713 
714 		ret = (*sdio->get_block)(dio->inode, fs_startblk,
715 						map_bh, create);
716 
717 		/* Store for completion */
718 		dio->private = map_bh->b_private;
719 
720 		if (ret == 0 && buffer_defer_completion(map_bh))
721 			ret = dio_set_defer_completion(dio);
722 	}
723 	return ret;
724 }
725 
726 /*
727  * There is no bio.  Make one now.
728  */
dio_new_bio(struct dio * dio,struct dio_submit * sdio,sector_t start_sector,struct buffer_head * map_bh)729 static inline int dio_new_bio(struct dio *dio, struct dio_submit *sdio,
730 		sector_t start_sector, struct buffer_head *map_bh)
731 {
732 	sector_t sector;
733 	int ret, nr_pages;
734 
735 	ret = dio_bio_reap(dio, sdio);
736 	if (ret)
737 		goto out;
738 	sector = start_sector << (sdio->blkbits - 9);
739 	nr_pages = min(sdio->pages_in_io, BIO_MAX_PAGES);
740 	BUG_ON(nr_pages <= 0);
741 	dio_bio_alloc(dio, sdio, map_bh->b_bdev, sector, nr_pages);
742 	sdio->boundary = 0;
743 out:
744 	return ret;
745 }
746 
747 /*
748  * Attempt to put the current chunk of 'cur_page' into the current BIO.  If
749  * that was successful then update final_block_in_bio and take a ref against
750  * the just-added page.
751  *
752  * Return zero on success.  Non-zero means the caller needs to start a new BIO.
753  */
dio_bio_add_page(struct dio_submit * sdio)754 static inline int dio_bio_add_page(struct dio_submit *sdio)
755 {
756 	int ret;
757 
758 	ret = bio_add_page(sdio->bio, sdio->cur_page,
759 			sdio->cur_page_len, sdio->cur_page_offset);
760 	if (ret == sdio->cur_page_len) {
761 		/*
762 		 * Decrement count only, if we are done with this page
763 		 */
764 		if ((sdio->cur_page_len + sdio->cur_page_offset) == PAGE_SIZE)
765 			sdio->pages_in_io--;
766 		get_page(sdio->cur_page);
767 		sdio->final_block_in_bio = sdio->cur_page_block +
768 			(sdio->cur_page_len >> sdio->blkbits);
769 		ret = 0;
770 	} else {
771 		ret = 1;
772 	}
773 	return ret;
774 }
775 
776 /*
777  * Put cur_page under IO.  The section of cur_page which is described by
778  * cur_page_offset,cur_page_len is put into a BIO.  The section of cur_page
779  * starts on-disk at cur_page_block.
780  *
781  * We take a ref against the page here (on behalf of its presence in the bio).
782  *
783  * The caller of this function is responsible for removing cur_page from the
784  * dio, and for dropping the refcount which came from that presence.
785  */
dio_send_cur_page(struct dio * dio,struct dio_submit * sdio,struct buffer_head * map_bh)786 static inline int dio_send_cur_page(struct dio *dio, struct dio_submit *sdio,
787 		struct buffer_head *map_bh)
788 {
789 	int ret = 0;
790 
791 	if (sdio->bio) {
792 		loff_t cur_offset = sdio->cur_page_fs_offset;
793 		loff_t bio_next_offset = sdio->logical_offset_in_bio +
794 			sdio->bio->bi_iter.bi_size;
795 
796 		/*
797 		 * See whether this new request is contiguous with the old.
798 		 *
799 		 * Btrfs cannot handle having logically non-contiguous requests
800 		 * submitted.  For example if you have
801 		 *
802 		 * Logical:  [0-4095][HOLE][8192-12287]
803 		 * Physical: [0-4095]      [4096-8191]
804 		 *
805 		 * We cannot submit those pages together as one BIO.  So if our
806 		 * current logical offset in the file does not equal what would
807 		 * be the next logical offset in the bio, submit the bio we
808 		 * have.
809 		 */
810 		if (sdio->final_block_in_bio != sdio->cur_page_block ||
811 		    cur_offset != bio_next_offset)
812 			dio_bio_submit(dio, sdio);
813 	}
814 
815 	if (sdio->bio == NULL) {
816 		ret = dio_new_bio(dio, sdio, sdio->cur_page_block, map_bh);
817 		if (ret)
818 			goto out;
819 	}
820 
821 	if (dio_bio_add_page(sdio) != 0) {
822 		dio_bio_submit(dio, sdio);
823 		ret = dio_new_bio(dio, sdio, sdio->cur_page_block, map_bh);
824 		if (ret == 0) {
825 			ret = dio_bio_add_page(sdio);
826 			BUG_ON(ret != 0);
827 		}
828 	}
829 out:
830 	return ret;
831 }
832 
833 /*
834  * An autonomous function to put a chunk of a page under deferred IO.
835  *
836  * The caller doesn't actually know (or care) whether this piece of page is in
837  * a BIO, or is under IO or whatever.  We just take care of all possible
838  * situations here.  The separation between the logic of do_direct_IO() and
839  * that of submit_page_section() is important for clarity.  Please don't break.
840  *
841  * The chunk of page starts on-disk at blocknr.
842  *
843  * We perform deferred IO, by recording the last-submitted page inside our
844  * private part of the dio structure.  If possible, we just expand the IO
845  * across that page here.
846  *
847  * If that doesn't work out then we put the old page into the bio and add this
848  * page to the dio instead.
849  */
850 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)851 submit_page_section(struct dio *dio, struct dio_submit *sdio, struct page *page,
852 		    unsigned offset, unsigned len, sector_t blocknr,
853 		    struct buffer_head *map_bh)
854 {
855 	int ret = 0;
856 
857 	if (dio->op == REQ_OP_WRITE) {
858 		/*
859 		 * Read accounting is performed in submit_bio()
860 		 */
861 		task_io_account_write(len);
862 	}
863 
864 	/*
865 	 * Can we just grow the current page's presence in the dio?
866 	 */
867 	if (sdio->cur_page == page &&
868 	    sdio->cur_page_offset + sdio->cur_page_len == offset &&
869 	    sdio->cur_page_block +
870 	    (sdio->cur_page_len >> sdio->blkbits) == blocknr) {
871 		sdio->cur_page_len += len;
872 		goto out;
873 	}
874 
875 	/*
876 	 * If there's a deferred page already there then send it.
877 	 */
878 	if (sdio->cur_page) {
879 		ret = dio_send_cur_page(dio, sdio, map_bh);
880 		put_page(sdio->cur_page);
881 		sdio->cur_page = NULL;
882 		if (ret)
883 			return ret;
884 	}
885 
886 	get_page(page);		/* It is in dio */
887 	sdio->cur_page = page;
888 	sdio->cur_page_offset = offset;
889 	sdio->cur_page_len = len;
890 	sdio->cur_page_block = blocknr;
891 	sdio->cur_page_fs_offset = sdio->block_in_file << sdio->blkbits;
892 out:
893 	/*
894 	 * If sdio->boundary then we want to schedule the IO now to
895 	 * avoid metadata seeks.
896 	 */
897 	if (sdio->boundary) {
898 		ret = dio_send_cur_page(dio, sdio, map_bh);
899 		if (sdio->bio)
900 			dio_bio_submit(dio, sdio);
901 		put_page(sdio->cur_page);
902 		sdio->cur_page = NULL;
903 	}
904 	return ret;
905 }
906 
907 /*
908  * If we are not writing the entire block and get_block() allocated
909  * the block for us, we need to fill-in the unused portion of the
910  * block with zeros. This happens only if user-buffer, fileoffset or
911  * io length is not filesystem block-size multiple.
912  *
913  * `end' is zero if we're doing the start of the IO, 1 at the end of the
914  * IO.
915  */
dio_zero_block(struct dio * dio,struct dio_submit * sdio,int end,struct buffer_head * map_bh)916 static inline void dio_zero_block(struct dio *dio, struct dio_submit *sdio,
917 		int end, struct buffer_head *map_bh)
918 {
919 	unsigned dio_blocks_per_fs_block;
920 	unsigned this_chunk_blocks;	/* In dio_blocks */
921 	unsigned this_chunk_bytes;
922 	struct page *page;
923 
924 	sdio->start_zero_done = 1;
925 	if (!sdio->blkfactor || !buffer_new(map_bh))
926 		return;
927 
928 	dio_blocks_per_fs_block = 1 << sdio->blkfactor;
929 	this_chunk_blocks = sdio->block_in_file & (dio_blocks_per_fs_block - 1);
930 
931 	if (!this_chunk_blocks)
932 		return;
933 
934 	/*
935 	 * We need to zero out part of an fs block.  It is either at the
936 	 * beginning or the end of the fs block.
937 	 */
938 	if (end)
939 		this_chunk_blocks = dio_blocks_per_fs_block - this_chunk_blocks;
940 
941 	this_chunk_bytes = this_chunk_blocks << sdio->blkbits;
942 
943 	page = ZERO_PAGE(0);
944 	if (submit_page_section(dio, sdio, page, 0, this_chunk_bytes,
945 				sdio->next_block_for_io, map_bh))
946 		return;
947 
948 	sdio->next_block_for_io += this_chunk_blocks;
949 }
950 
951 /*
952  * Walk the user pages, and the file, mapping blocks to disk and generating
953  * a sequence of (page,offset,len,block) mappings.  These mappings are injected
954  * into submit_page_section(), which takes care of the next stage of submission
955  *
956  * Direct IO against a blockdev is different from a file.  Because we can
957  * happily perform page-sized but 512-byte aligned IOs.  It is important that
958  * blockdev IO be able to have fine alignment and large sizes.
959  *
960  * So what we do is to permit the ->get_block function to populate bh.b_size
961  * with the size of IO which is permitted at this offset and this i_blkbits.
962  *
963  * For best results, the blockdev should be set up with 512-byte i_blkbits and
964  * it should set b_size to PAGE_SIZE or more inside get_block().  This gives
965  * fine alignment but still allows this function to work in PAGE_SIZE units.
966  */
do_direct_IO(struct dio * dio,struct dio_submit * sdio,struct buffer_head * map_bh)967 static int do_direct_IO(struct dio *dio, struct dio_submit *sdio,
968 			struct buffer_head *map_bh)
969 {
970 	const unsigned blkbits = sdio->blkbits;
971 	const unsigned i_blkbits = blkbits + sdio->blkfactor;
972 	int ret = 0;
973 
974 	while (sdio->block_in_file < sdio->final_block_in_request) {
975 		struct page *page;
976 		size_t from, to;
977 
978 		page = dio_get_page(dio, sdio);
979 		if (IS_ERR(page)) {
980 			ret = PTR_ERR(page);
981 			goto out;
982 		}
983 		from = sdio->head ? 0 : sdio->from;
984 		to = (sdio->head == sdio->tail - 1) ? sdio->to : PAGE_SIZE;
985 		sdio->head++;
986 
987 		while (from < to) {
988 			unsigned this_chunk_bytes;	/* # of bytes mapped */
989 			unsigned this_chunk_blocks;	/* # of blocks */
990 			unsigned u;
991 
992 			if (sdio->blocks_available == 0) {
993 				/*
994 				 * Need to go and map some more disk
995 				 */
996 				unsigned long blkmask;
997 				unsigned long dio_remainder;
998 
999 				ret = get_more_blocks(dio, sdio, map_bh);
1000 				if (ret) {
1001 					put_page(page);
1002 					goto out;
1003 				}
1004 				if (!buffer_mapped(map_bh))
1005 					goto do_holes;
1006 
1007 				sdio->blocks_available =
1008 						map_bh->b_size >> blkbits;
1009 				sdio->next_block_for_io =
1010 					map_bh->b_blocknr << sdio->blkfactor;
1011 				if (buffer_new(map_bh)) {
1012 					clean_bdev_aliases(
1013 						map_bh->b_bdev,
1014 						map_bh->b_blocknr,
1015 						map_bh->b_size >> i_blkbits);
1016 				}
1017 
1018 				if (!sdio->blkfactor)
1019 					goto do_holes;
1020 
1021 				blkmask = (1 << sdio->blkfactor) - 1;
1022 				dio_remainder = (sdio->block_in_file & blkmask);
1023 
1024 				/*
1025 				 * If we are at the start of IO and that IO
1026 				 * starts partway into a fs-block,
1027 				 * dio_remainder will be non-zero.  If the IO
1028 				 * is a read then we can simply advance the IO
1029 				 * cursor to the first block which is to be
1030 				 * read.  But if the IO is a write and the
1031 				 * block was newly allocated we cannot do that;
1032 				 * the start of the fs block must be zeroed out
1033 				 * on-disk
1034 				 */
1035 				if (!buffer_new(map_bh))
1036 					sdio->next_block_for_io += dio_remainder;
1037 				sdio->blocks_available -= dio_remainder;
1038 			}
1039 do_holes:
1040 			/* Handle holes */
1041 			if (!buffer_mapped(map_bh)) {
1042 				loff_t i_size_aligned;
1043 
1044 				/* AKPM: eargh, -ENOTBLK is a hack */
1045 				if (dio->op == REQ_OP_WRITE) {
1046 					put_page(page);
1047 					return -ENOTBLK;
1048 				}
1049 
1050 				/*
1051 				 * Be sure to account for a partial block as the
1052 				 * last block in the file
1053 				 */
1054 				i_size_aligned = ALIGN(i_size_read(dio->inode),
1055 							1 << blkbits);
1056 				if (sdio->block_in_file >=
1057 						i_size_aligned >> blkbits) {
1058 					/* We hit eof */
1059 					put_page(page);
1060 					goto out;
1061 				}
1062 				zero_user(page, from, 1 << blkbits);
1063 				sdio->block_in_file++;
1064 				from += 1 << blkbits;
1065 				dio->result += 1 << blkbits;
1066 				goto next_block;
1067 			}
1068 
1069 			/*
1070 			 * If we're performing IO which has an alignment which
1071 			 * is finer than the underlying fs, go check to see if
1072 			 * we must zero out the start of this block.
1073 			 */
1074 			if (unlikely(sdio->blkfactor && !sdio->start_zero_done))
1075 				dio_zero_block(dio, sdio, 0, map_bh);
1076 
1077 			/*
1078 			 * Work out, in this_chunk_blocks, how much disk we
1079 			 * can add to this page
1080 			 */
1081 			this_chunk_blocks = sdio->blocks_available;
1082 			u = (to - from) >> blkbits;
1083 			if (this_chunk_blocks > u)
1084 				this_chunk_blocks = u;
1085 			u = sdio->final_block_in_request - sdio->block_in_file;
1086 			if (this_chunk_blocks > u)
1087 				this_chunk_blocks = u;
1088 			this_chunk_bytes = this_chunk_blocks << blkbits;
1089 			BUG_ON(this_chunk_bytes == 0);
1090 
1091 			if (this_chunk_blocks == sdio->blocks_available)
1092 				sdio->boundary = buffer_boundary(map_bh);
1093 			ret = submit_page_section(dio, sdio, page,
1094 						  from,
1095 						  this_chunk_bytes,
1096 						  sdio->next_block_for_io,
1097 						  map_bh);
1098 			if (ret) {
1099 				put_page(page);
1100 				goto out;
1101 			}
1102 			sdio->next_block_for_io += this_chunk_blocks;
1103 
1104 			sdio->block_in_file += this_chunk_blocks;
1105 			from += this_chunk_bytes;
1106 			dio->result += this_chunk_bytes;
1107 			sdio->blocks_available -= this_chunk_blocks;
1108 next_block:
1109 			BUG_ON(sdio->block_in_file > sdio->final_block_in_request);
1110 			if (sdio->block_in_file == sdio->final_block_in_request)
1111 				break;
1112 		}
1113 
1114 		/* Drop the ref which was taken in get_user_pages() */
1115 		put_page(page);
1116 	}
1117 out:
1118 	return ret;
1119 }
1120 
drop_refcount(struct dio * dio)1121 static inline int drop_refcount(struct dio *dio)
1122 {
1123 	int ret2;
1124 	unsigned long flags;
1125 
1126 	/*
1127 	 * Sync will always be dropping the final ref and completing the
1128 	 * operation.  AIO can if it was a broken operation described above or
1129 	 * in fact if all the bios race to complete before we get here.  In
1130 	 * that case dio_complete() translates the EIOCBQUEUED into the proper
1131 	 * return code that the caller will hand to ->complete().
1132 	 *
1133 	 * This is managed by the bio_lock instead of being an atomic_t so that
1134 	 * completion paths can drop their ref and use the remaining count to
1135 	 * decide to wake the submission path atomically.
1136 	 */
1137 	spin_lock_irqsave(&dio->bio_lock, flags);
1138 	ret2 = --dio->refcount;
1139 	spin_unlock_irqrestore(&dio->bio_lock, flags);
1140 	return ret2;
1141 }
1142 
1143 /*
1144  * This is a library function for use by filesystem drivers.
1145  *
1146  * The locking rules are governed by the flags parameter:
1147  *  - if the flags value contains DIO_LOCKING we use a fancy locking
1148  *    scheme for dumb filesystems.
1149  *    For writes this function is called under i_mutex and returns with
1150  *    i_mutex held, for reads, i_mutex is not held on entry, but it is
1151  *    taken and dropped again before returning.
1152  *  - if the flags value does NOT contain DIO_LOCKING we don't use any
1153  *    internal locking but rather rely on the filesystem to synchronize
1154  *    direct I/O reads/writes versus each other and truncate.
1155  *
1156  * To help with locking against truncate we incremented the i_dio_count
1157  * counter before starting direct I/O, and decrement it once we are done.
1158  * Truncate can wait for it to reach zero to provide exclusion.  It is
1159  * expected that filesystem provide exclusion between new direct I/O
1160  * and truncates.  For DIO_LOCKING filesystems this is done by i_mutex,
1161  * but other filesystems need to take care of this on their own.
1162  *
1163  * NOTE: if you pass "sdio" to anything by pointer make sure that function
1164  * is always inlined. Otherwise gcc is unable to split the structure into
1165  * individual fields and will generate much worse code. This is important
1166  * for the whole file.
1167  */
1168 static inline ssize_t
do_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,dio_submit_t submit_io,int flags)1169 do_blockdev_direct_IO(struct kiocb *iocb, struct inode *inode,
1170 		      struct block_device *bdev, struct iov_iter *iter,
1171 		      get_block_t get_block, dio_iodone_t end_io,
1172 		      dio_submit_t submit_io, int flags)
1173 {
1174 	unsigned i_blkbits = READ_ONCE(inode->i_blkbits);
1175 	unsigned blkbits = i_blkbits;
1176 	unsigned blocksize_mask = (1 << blkbits) - 1;
1177 	ssize_t retval = -EINVAL;
1178 	const size_t count = iov_iter_count(iter);
1179 	loff_t offset = iocb->ki_pos;
1180 	const loff_t end = offset + count;
1181 	struct dio *dio;
1182 	struct dio_submit sdio = { 0, };
1183 	struct buffer_head map_bh = { 0, };
1184 	struct blk_plug plug;
1185 	unsigned long align = offset | iov_iter_alignment(iter);
1186 
1187 	/*
1188 	 * Avoid references to bdev if not absolutely needed to give
1189 	 * the early prefetch in the caller enough time.
1190 	 */
1191 
1192 	if (align & blocksize_mask) {
1193 		if (bdev)
1194 			blkbits = blksize_bits(bdev_logical_block_size(bdev));
1195 		blocksize_mask = (1 << blkbits) - 1;
1196 		if (align & blocksize_mask)
1197 			goto out;
1198 	}
1199 
1200 	/* watch out for a 0 len io from a tricksy fs */
1201 	if (iov_iter_rw(iter) == READ && !count)
1202 		return 0;
1203 
1204 	dio = kmem_cache_alloc(dio_cache, GFP_KERNEL);
1205 	retval = -ENOMEM;
1206 	if (!dio)
1207 		goto out;
1208 	/*
1209 	 * Believe it or not, zeroing out the page array caused a .5%
1210 	 * performance regression in a database benchmark.  So, we take
1211 	 * care to only zero out what's needed.
1212 	 */
1213 	memset(dio, 0, offsetof(struct dio, pages));
1214 
1215 	dio->flags = flags;
1216 	if (dio->flags & DIO_LOCKING) {
1217 		if (iov_iter_rw(iter) == READ) {
1218 			struct address_space *mapping =
1219 					iocb->ki_filp->f_mapping;
1220 
1221 			/* will be released by direct_io_worker */
1222 			inode_lock(inode);
1223 
1224 			retval = filemap_write_and_wait_range(mapping, offset,
1225 							      end - 1);
1226 			if (retval) {
1227 				inode_unlock(inode);
1228 				kmem_cache_free(dio_cache, dio);
1229 				goto out;
1230 			}
1231 		}
1232 	}
1233 
1234 	/* Once we sampled i_size check for reads beyond EOF */
1235 	dio->i_size = i_size_read(inode);
1236 	if (iov_iter_rw(iter) == READ && offset >= dio->i_size) {
1237 		if (dio->flags & DIO_LOCKING)
1238 			inode_unlock(inode);
1239 		kmem_cache_free(dio_cache, dio);
1240 		retval = 0;
1241 		goto out;
1242 	}
1243 
1244 	/*
1245 	 * For file extending writes updating i_size before data writeouts
1246 	 * complete can expose uninitialized blocks in dumb filesystems.
1247 	 * In that case we need to wait for I/O completion even if asked
1248 	 * for an asynchronous write.
1249 	 */
1250 	if (is_sync_kiocb(iocb))
1251 		dio->is_async = false;
1252 	else if (iov_iter_rw(iter) == WRITE && end > i_size_read(inode))
1253 		dio->is_async = false;
1254 	else
1255 		dio->is_async = true;
1256 
1257 	dio->inode = inode;
1258 	if (iov_iter_rw(iter) == WRITE) {
1259 		dio->op = REQ_OP_WRITE;
1260 		dio->op_flags = REQ_SYNC | REQ_IDLE;
1261 		if (iocb->ki_flags & IOCB_NOWAIT)
1262 			dio->op_flags |= REQ_NOWAIT;
1263 	} else {
1264 		dio->op = REQ_OP_READ;
1265 	}
1266 	if (iocb->ki_flags & IOCB_HIPRI)
1267 		dio->op_flags |= REQ_HIPRI;
1268 
1269 	/*
1270 	 * For AIO O_(D)SYNC writes we need to defer completions to a workqueue
1271 	 * so that we can call ->fsync.
1272 	 */
1273 	if (dio->is_async && iov_iter_rw(iter) == WRITE) {
1274 		retval = 0;
1275 		if (iocb->ki_flags & IOCB_DSYNC)
1276 			retval = dio_set_defer_completion(dio);
1277 		else if (!dio->inode->i_sb->s_dio_done_wq) {
1278 			/*
1279 			 * In case of AIO write racing with buffered read we
1280 			 * need to defer completion. We can't decide this now,
1281 			 * however the workqueue needs to be initialized here.
1282 			 */
1283 			retval = sb_init_dio_done_wq(dio->inode->i_sb);
1284 		}
1285 		if (retval) {
1286 			/*
1287 			 * We grab i_mutex only for reads so we don't have
1288 			 * to release it here
1289 			 */
1290 			kmem_cache_free(dio_cache, dio);
1291 			goto out;
1292 		}
1293 	}
1294 
1295 	/*
1296 	 * Will be decremented at I/O completion time.
1297 	 */
1298 	inode_dio_begin(inode);
1299 
1300 	retval = 0;
1301 	sdio.blkbits = blkbits;
1302 	sdio.blkfactor = i_blkbits - blkbits;
1303 	sdio.block_in_file = offset >> blkbits;
1304 
1305 	sdio.get_block = get_block;
1306 	dio->end_io = end_io;
1307 	sdio.submit_io = submit_io;
1308 	sdio.final_block_in_bio = -1;
1309 	sdio.next_block_for_io = -1;
1310 
1311 	dio->iocb = iocb;
1312 
1313 	spin_lock_init(&dio->bio_lock);
1314 	dio->refcount = 1;
1315 
1316 	dio->should_dirty = iter_is_iovec(iter) && iov_iter_rw(iter) == READ;
1317 	sdio.iter = iter;
1318 	sdio.final_block_in_request = end >> blkbits;
1319 
1320 	/*
1321 	 * In case of non-aligned buffers, we may need 2 more
1322 	 * pages since we need to zero out first and last block.
1323 	 */
1324 	if (unlikely(sdio.blkfactor))
1325 		sdio.pages_in_io = 2;
1326 
1327 	sdio.pages_in_io += iov_iter_npages(iter, INT_MAX);
1328 
1329 	blk_start_plug(&plug);
1330 
1331 	retval = do_direct_IO(dio, &sdio, &map_bh);
1332 	if (retval)
1333 		dio_cleanup(dio, &sdio);
1334 
1335 	if (retval == -ENOTBLK) {
1336 		/*
1337 		 * The remaining part of the request will be
1338 		 * be handled by buffered I/O when we return
1339 		 */
1340 		retval = 0;
1341 	}
1342 	/*
1343 	 * There may be some unwritten disk at the end of a part-written
1344 	 * fs-block-sized block.  Go zero that now.
1345 	 */
1346 	dio_zero_block(dio, &sdio, 1, &map_bh);
1347 
1348 	if (sdio.cur_page) {
1349 		ssize_t ret2;
1350 
1351 		ret2 = dio_send_cur_page(dio, &sdio, &map_bh);
1352 		if (retval == 0)
1353 			retval = ret2;
1354 		put_page(sdio.cur_page);
1355 		sdio.cur_page = NULL;
1356 	}
1357 	if (sdio.bio)
1358 		dio_bio_submit(dio, &sdio);
1359 
1360 	blk_finish_plug(&plug);
1361 
1362 	/*
1363 	 * It is possible that, we return short IO due to end of file.
1364 	 * In that case, we need to release all the pages we got hold on.
1365 	 */
1366 	dio_cleanup(dio, &sdio);
1367 
1368 	/*
1369 	 * All block lookups have been performed. For READ requests
1370 	 * we can let i_mutex go now that its achieved its purpose
1371 	 * of protecting us from looking up uninitialized blocks.
1372 	 */
1373 	if (iov_iter_rw(iter) == READ && (dio->flags & DIO_LOCKING))
1374 		inode_unlock(dio->inode);
1375 
1376 	/*
1377 	 * The only time we want to leave bios in flight is when a successful
1378 	 * partial aio read or full aio write have been setup.  In that case
1379 	 * bio completion will call aio_complete.  The only time it's safe to
1380 	 * call aio_complete is when we return -EIOCBQUEUED, so we key on that.
1381 	 * This had *better* be the only place that raises -EIOCBQUEUED.
1382 	 */
1383 	BUG_ON(retval == -EIOCBQUEUED);
1384 	if (dio->is_async && retval == 0 && dio->result &&
1385 	    (iov_iter_rw(iter) == READ || dio->result == count))
1386 		retval = -EIOCBQUEUED;
1387 	else
1388 		dio_await_completion(dio);
1389 
1390 	if (drop_refcount(dio) == 0) {
1391 		retval = dio_complete(dio, retval, DIO_COMPLETE_INVALIDATE);
1392 	} else
1393 		BUG_ON(retval != -EIOCBQUEUED);
1394 
1395 out:
1396 	return retval;
1397 }
1398 
__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,dio_submit_t submit_io,int flags)1399 ssize_t __blockdev_direct_IO(struct kiocb *iocb, struct inode *inode,
1400 			     struct block_device *bdev, struct iov_iter *iter,
1401 			     get_block_t get_block,
1402 			     dio_iodone_t end_io, dio_submit_t submit_io,
1403 			     int flags)
1404 {
1405 	/*
1406 	 * The block device state is needed in the end to finally
1407 	 * submit everything.  Since it's likely to be cache cold
1408 	 * prefetch it here as first thing to hide some of the
1409 	 * latency.
1410 	 *
1411 	 * Attempt to prefetch the pieces we likely need later.
1412 	 */
1413 	prefetch(&bdev->bd_disk->part_tbl);
1414 	prefetch(bdev->bd_queue);
1415 	prefetch((char *)bdev->bd_queue + SMP_CACHE_BYTES);
1416 
1417 	return do_blockdev_direct_IO(iocb, inode, bdev, iter, get_block,
1418 				     end_io, submit_io, flags);
1419 }
1420 
1421 EXPORT_SYMBOL(__blockdev_direct_IO);
1422 
dio_init(void)1423 static __init int dio_init(void)
1424 {
1425 	dio_cache = KMEM_CACHE(dio, SLAB_PANIC);
1426 	return 0;
1427 }
1428 module_init(dio_init)
1429