xref: /linux/fs/direct-io.c (revision d67b569f5f620c0fb95d5212642746b7ba9d29e4)
1 /*
2  * fs/direct-io.c
3  *
4  * Copyright (C) 2002, Linus Torvalds.
5  *
6  * O_DIRECT
7  *
8  * 04Jul2002	akpm@zip.com.au
9  *		Initial version
10  * 11Sep2002	janetinc@us.ibm.com
11  * 		added readv/writev support.
12  * 29Oct2002	akpm@zip.com.au
13  *		rewrote bio_add_page() support.
14  * 30Oct2002	pbadari@us.ibm.com
15  *		added support for non-aligned IO.
16  * 06Nov2002	pbadari@us.ibm.com
17  *		added asynchronous IO support.
18  * 21Jul2003	nathans@sgi.com
19  *		added IO completion notifier.
20  */
21 
22 #include <linux/kernel.h>
23 #include <linux/module.h>
24 #include <linux/types.h>
25 #include <linux/fs.h>
26 #include <linux/mm.h>
27 #include <linux/slab.h>
28 #include <linux/highmem.h>
29 #include <linux/pagemap.h>
30 #include <linux/bio.h>
31 #include <linux/wait.h>
32 #include <linux/err.h>
33 #include <linux/blkdev.h>
34 #include <linux/buffer_head.h>
35 #include <linux/rwsem.h>
36 #include <linux/uio.h>
37 #include <asm/atomic.h>
38 
39 /*
40  * How many user pages to map in one call to get_user_pages().  This determines
41  * the size of a structure on the stack.
42  */
43 #define DIO_PAGES	64
44 
45 /*
46  * This code generally works in units of "dio_blocks".  A dio_block is
47  * somewhere between the hard sector size and the filesystem block size.  it
48  * is determined on a per-invocation basis.   When talking to the filesystem
49  * we need to convert dio_blocks to fs_blocks by scaling the dio_block quantity
50  * down by dio->blkfactor.  Similarly, fs-blocksize quantities are converted
51  * to bio_block quantities by shifting left by blkfactor.
52  *
53  * If blkfactor is zero then the user's request was aligned to the filesystem's
54  * blocksize.
55  *
56  * lock_type is DIO_LOCKING for regular files on direct-IO-naive filesystems.
57  * This determines whether we need to do the fancy locking which prevents
58  * direct-IO from being able to read uninitialised disk blocks.  If its zero
59  * (blockdev) this locking is not done, and if it is DIO_OWN_LOCKING i_sem is
60  * not held for the entire direct write (taken briefly, initially, during a
61  * direct read though, but its never held for the duration of a direct-IO).
62  */
63 
64 struct dio {
65 	/* BIO submission state */
66 	struct bio *bio;		/* bio under assembly */
67 	struct inode *inode;
68 	int rw;
69 	loff_t i_size;			/* i_size when submitted */
70 	int lock_type;			/* doesn't change */
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 	size_t	size;			/* total request size (doesn't change)*/
82 	sector_t block_in_file;		/* Current offset into the underlying
83 					   file in dio_block units. */
84 	unsigned blocks_available;	/* At block_in_file.  changes */
85 	sector_t final_block_in_request;/* doesn't change */
86 	unsigned first_block_in_page;	/* doesn't change, Used only once */
87 	int boundary;			/* prev block is at a boundary */
88 	int reap_counter;		/* rate limit reaping */
89 	get_blocks_t *get_blocks;	/* block mapping function */
90 	dio_iodone_t *end_io;		/* IO completion function */
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 	struct buffer_head map_bh;	/* last get_blocks() result */
95 
96 	/*
97 	 * Deferred addition of a page to the dio.  These variables are
98 	 * private to dio_send_cur_page(), submit_page_section() and
99 	 * dio_bio_add_page().
100 	 */
101 	struct page *cur_page;		/* The page */
102 	unsigned cur_page_offset;	/* Offset into it, in bytes */
103 	unsigned cur_page_len;		/* Nr of bytes at cur_page_offset */
104 	sector_t cur_page_block;	/* Where it starts */
105 
106 	/*
107 	 * Page fetching state. These variables belong to dio_refill_pages().
108 	 */
109 	int curr_page;			/* changes */
110 	int total_pages;		/* doesn't change */
111 	unsigned long curr_user_address;/* changes */
112 
113 	/*
114 	 * Page queue.  These variables belong to dio_refill_pages() and
115 	 * dio_get_page().
116 	 */
117 	struct page *pages[DIO_PAGES];	/* page buffer */
118 	unsigned head;			/* next page to process */
119 	unsigned tail;			/* last valid page + 1 */
120 	int page_errors;		/* errno from get_user_pages() */
121 
122 	/* BIO completion state */
123 	spinlock_t bio_lock;		/* protects BIO fields below */
124 	int bio_count;			/* nr bios to be completed */
125 	int bios_in_flight;		/* nr bios in flight */
126 	struct bio *bio_list;		/* singly linked via bi_private */
127 	struct task_struct *waiter;	/* waiting task (NULL if none) */
128 
129 	/* AIO related stuff */
130 	struct kiocb *iocb;		/* kiocb */
131 	int is_async;			/* is IO async ? */
132 	ssize_t result;                 /* IO result */
133 };
134 
135 /*
136  * How many pages are in the queue?
137  */
138 static inline unsigned dio_pages_present(struct dio *dio)
139 {
140 	return dio->tail - dio->head;
141 }
142 
143 /*
144  * Go grab and pin some userspace pages.   Typically we'll get 64 at a time.
145  */
146 static int dio_refill_pages(struct dio *dio)
147 {
148 	int ret;
149 	int nr_pages;
150 
151 	nr_pages = min(dio->total_pages - dio->curr_page, DIO_PAGES);
152 	down_read(&current->mm->mmap_sem);
153 	ret = get_user_pages(
154 		current,			/* Task for fault acounting */
155 		current->mm,			/* whose pages? */
156 		dio->curr_user_address,		/* Where from? */
157 		nr_pages,			/* How many pages? */
158 		dio->rw == READ,		/* Write to memory? */
159 		0,				/* force (?) */
160 		&dio->pages[0],
161 		NULL);				/* vmas */
162 	up_read(&current->mm->mmap_sem);
163 
164 	if (ret < 0 && dio->blocks_available && (dio->rw == WRITE)) {
165 		/*
166 		 * A memory fault, but the filesystem has some outstanding
167 		 * mapped blocks.  We need to use those blocks up to avoid
168 		 * leaking stale data in the file.
169 		 */
170 		if (dio->page_errors == 0)
171 			dio->page_errors = ret;
172 		dio->pages[0] = ZERO_PAGE(dio->curr_user_address);
173 		dio->head = 0;
174 		dio->tail = 1;
175 		ret = 0;
176 		goto out;
177 	}
178 
179 	if (ret >= 0) {
180 		dio->curr_user_address += ret * PAGE_SIZE;
181 		dio->curr_page += ret;
182 		dio->head = 0;
183 		dio->tail = ret;
184 		ret = 0;
185 	}
186 out:
187 	return ret;
188 }
189 
190 /*
191  * Get another userspace page.  Returns an ERR_PTR on error.  Pages are
192  * buffered inside the dio so that we can call get_user_pages() against a
193  * decent number of pages, less frequently.  To provide nicer use of the
194  * L1 cache.
195  */
196 static struct page *dio_get_page(struct dio *dio)
197 {
198 	if (dio_pages_present(dio) == 0) {
199 		int ret;
200 
201 		ret = dio_refill_pages(dio);
202 		if (ret)
203 			return ERR_PTR(ret);
204 		BUG_ON(dio_pages_present(dio) == 0);
205 	}
206 	return dio->pages[dio->head++];
207 }
208 
209 /*
210  * Called when all DIO BIO I/O has been completed - let the filesystem
211  * know, if it registered an interest earlier via get_blocks.  Pass the
212  * private field of the map buffer_head so that filesystems can use it
213  * to hold additional state between get_blocks calls and dio_complete.
214  */
215 static void dio_complete(struct dio *dio, loff_t offset, ssize_t bytes)
216 {
217 	if (dio->end_io && dio->result)
218 		dio->end_io(dio->iocb, offset, bytes, dio->map_bh.b_private);
219 	if (dio->lock_type == DIO_LOCKING)
220 		up_read(&dio->inode->i_alloc_sem);
221 }
222 
223 /*
224  * Called when a BIO has been processed.  If the count goes to zero then IO is
225  * complete and we can signal this to the AIO layer.
226  */
227 static void finished_one_bio(struct dio *dio)
228 {
229 	unsigned long flags;
230 
231 	spin_lock_irqsave(&dio->bio_lock, flags);
232 	if (dio->bio_count == 1) {
233 		if (dio->is_async) {
234 			ssize_t transferred;
235 			loff_t offset;
236 
237 			/*
238 			 * Last reference to the dio is going away.
239 			 * Drop spinlock and complete the DIO.
240 			 */
241 			spin_unlock_irqrestore(&dio->bio_lock, flags);
242 
243 			/* Check for short read case */
244 			transferred = dio->result;
245 			offset = dio->iocb->ki_pos;
246 
247 			if ((dio->rw == READ) &&
248 			    ((offset + transferred) > dio->i_size))
249 				transferred = dio->i_size - offset;
250 
251 			dio_complete(dio, offset, transferred);
252 
253 			/* Complete AIO later if falling back to buffered i/o */
254 			if (dio->result == dio->size ||
255 				((dio->rw == READ) && dio->result)) {
256 				aio_complete(dio->iocb, transferred, 0);
257 				kfree(dio);
258 				return;
259 			} else {
260 				/*
261 				 * Falling back to buffered
262 				 */
263 				spin_lock_irqsave(&dio->bio_lock, flags);
264 				dio->bio_count--;
265 				if (dio->waiter)
266 					wake_up_process(dio->waiter);
267 				spin_unlock_irqrestore(&dio->bio_lock, flags);
268 				return;
269 			}
270 		}
271 	}
272 	dio->bio_count--;
273 	spin_unlock_irqrestore(&dio->bio_lock, flags);
274 }
275 
276 static int dio_bio_complete(struct dio *dio, struct bio *bio);
277 /*
278  * Asynchronous IO callback.
279  */
280 static int dio_bio_end_aio(struct bio *bio, unsigned int bytes_done, int error)
281 {
282 	struct dio *dio = bio->bi_private;
283 
284 	if (bio->bi_size)
285 		return 1;
286 
287 	/* cleanup the bio */
288 	dio_bio_complete(dio, bio);
289 	return 0;
290 }
291 
292 /*
293  * The BIO completion handler simply queues the BIO up for the process-context
294  * handler.
295  *
296  * During I/O bi_private points at the dio.  After I/O, bi_private is used to
297  * implement a singly-linked list of completed BIOs, at dio->bio_list.
298  */
299 static int dio_bio_end_io(struct bio *bio, unsigned int bytes_done, int error)
300 {
301 	struct dio *dio = bio->bi_private;
302 	unsigned long flags;
303 
304 	if (bio->bi_size)
305 		return 1;
306 
307 	spin_lock_irqsave(&dio->bio_lock, flags);
308 	bio->bi_private = dio->bio_list;
309 	dio->bio_list = bio;
310 	dio->bios_in_flight--;
311 	if (dio->waiter && dio->bios_in_flight == 0)
312 		wake_up_process(dio->waiter);
313 	spin_unlock_irqrestore(&dio->bio_lock, flags);
314 	return 0;
315 }
316 
317 static int
318 dio_bio_alloc(struct dio *dio, struct block_device *bdev,
319 		sector_t first_sector, int nr_vecs)
320 {
321 	struct bio *bio;
322 
323 	bio = bio_alloc(GFP_KERNEL, nr_vecs);
324 	if (bio == NULL)
325 		return -ENOMEM;
326 
327 	bio->bi_bdev = bdev;
328 	bio->bi_sector = first_sector;
329 	if (dio->is_async)
330 		bio->bi_end_io = dio_bio_end_aio;
331 	else
332 		bio->bi_end_io = dio_bio_end_io;
333 
334 	dio->bio = bio;
335 	return 0;
336 }
337 
338 /*
339  * In the AIO read case we speculatively dirty the pages before starting IO.
340  * During IO completion, any of these pages which happen to have been written
341  * back will be redirtied by bio_check_pages_dirty().
342  */
343 static void dio_bio_submit(struct dio *dio)
344 {
345 	struct bio *bio = dio->bio;
346 	unsigned long flags;
347 
348 	bio->bi_private = dio;
349 	spin_lock_irqsave(&dio->bio_lock, flags);
350 	dio->bio_count++;
351 	dio->bios_in_flight++;
352 	spin_unlock_irqrestore(&dio->bio_lock, flags);
353 	if (dio->is_async && dio->rw == READ)
354 		bio_set_pages_dirty(bio);
355 	submit_bio(dio->rw, bio);
356 
357 	dio->bio = NULL;
358 	dio->boundary = 0;
359 }
360 
361 /*
362  * Release any resources in case of a failure
363  */
364 static void dio_cleanup(struct dio *dio)
365 {
366 	while (dio_pages_present(dio))
367 		page_cache_release(dio_get_page(dio));
368 }
369 
370 /*
371  * Wait for the next BIO to complete.  Remove it and return it.
372  */
373 static struct bio *dio_await_one(struct dio *dio)
374 {
375 	unsigned long flags;
376 	struct bio *bio;
377 
378 	spin_lock_irqsave(&dio->bio_lock, flags);
379 	while (dio->bio_list == NULL) {
380 		set_current_state(TASK_UNINTERRUPTIBLE);
381 		if (dio->bio_list == NULL) {
382 			dio->waiter = current;
383 			spin_unlock_irqrestore(&dio->bio_lock, flags);
384 			blk_run_address_space(dio->inode->i_mapping);
385 			io_schedule();
386 			spin_lock_irqsave(&dio->bio_lock, flags);
387 			dio->waiter = NULL;
388 		}
389 		set_current_state(TASK_RUNNING);
390 	}
391 	bio = dio->bio_list;
392 	dio->bio_list = bio->bi_private;
393 	spin_unlock_irqrestore(&dio->bio_lock, flags);
394 	return bio;
395 }
396 
397 /*
398  * Process one completed BIO.  No locks are held.
399  */
400 static int dio_bio_complete(struct dio *dio, struct bio *bio)
401 {
402 	const int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
403 	struct bio_vec *bvec = bio->bi_io_vec;
404 	int page_no;
405 
406 	if (!uptodate)
407 		dio->result = -EIO;
408 
409 	if (dio->is_async && dio->rw == READ) {
410 		bio_check_pages_dirty(bio);	/* transfers ownership */
411 	} else {
412 		for (page_no = 0; page_no < bio->bi_vcnt; page_no++) {
413 			struct page *page = bvec[page_no].bv_page;
414 
415 			if (dio->rw == READ && !PageCompound(page))
416 				set_page_dirty_lock(page);
417 			page_cache_release(page);
418 		}
419 		bio_put(bio);
420 	}
421 	finished_one_bio(dio);
422 	return uptodate ? 0 : -EIO;
423 }
424 
425 /*
426  * Wait on and process all in-flight BIOs.
427  */
428 static int dio_await_completion(struct dio *dio)
429 {
430 	int ret = 0;
431 
432 	if (dio->bio)
433 		dio_bio_submit(dio);
434 
435 	/*
436 	 * The bio_lock is not held for the read of bio_count.
437 	 * This is ok since it is the dio_bio_complete() that changes
438 	 * bio_count.
439 	 */
440 	while (dio->bio_count) {
441 		struct bio *bio = dio_await_one(dio);
442 		int ret2;
443 
444 		ret2 = dio_bio_complete(dio, bio);
445 		if (ret == 0)
446 			ret = ret2;
447 	}
448 	return ret;
449 }
450 
451 /*
452  * A really large O_DIRECT read or write can generate a lot of BIOs.  So
453  * to keep the memory consumption sane we periodically reap any completed BIOs
454  * during the BIO generation phase.
455  *
456  * This also helps to limit the peak amount of pinned userspace memory.
457  */
458 static int dio_bio_reap(struct dio *dio)
459 {
460 	int ret = 0;
461 
462 	if (dio->reap_counter++ >= 64) {
463 		while (dio->bio_list) {
464 			unsigned long flags;
465 			struct bio *bio;
466 			int ret2;
467 
468 			spin_lock_irqsave(&dio->bio_lock, flags);
469 			bio = dio->bio_list;
470 			dio->bio_list = bio->bi_private;
471 			spin_unlock_irqrestore(&dio->bio_lock, flags);
472 			ret2 = dio_bio_complete(dio, bio);
473 			if (ret == 0)
474 				ret = ret2;
475 		}
476 		dio->reap_counter = 0;
477 	}
478 	return ret;
479 }
480 
481 /*
482  * Call into the fs to map some more disk blocks.  We record the current number
483  * of available blocks at dio->blocks_available.  These are in units of the
484  * fs blocksize, (1 << inode->i_blkbits).
485  *
486  * The fs is allowed to map lots of blocks at once.  If it wants to do that,
487  * it uses the passed inode-relative block number as the file offset, as usual.
488  *
489  * get_blocks() is passed the number of i_blkbits-sized blocks which direct_io
490  * has remaining to do.  The fs should not map more than this number of blocks.
491  *
492  * If the fs has mapped a lot of blocks, it should populate bh->b_size to
493  * indicate how much contiguous disk space has been made available at
494  * bh->b_blocknr.
495  *
496  * If *any* of the mapped blocks are new, then the fs must set buffer_new().
497  * This isn't very efficient...
498  *
499  * In the case of filesystem holes: the fs may return an arbitrarily-large
500  * hole by returning an appropriate value in b_size and by clearing
501  * buffer_mapped().  However the direct-io code will only process holes one
502  * block at a time - it will repeatedly call get_blocks() as it walks the hole.
503  */
504 static int get_more_blocks(struct dio *dio)
505 {
506 	int ret;
507 	struct buffer_head *map_bh = &dio->map_bh;
508 	sector_t fs_startblk;	/* Into file, in filesystem-sized blocks */
509 	unsigned long fs_count;	/* Number of filesystem-sized blocks */
510 	unsigned long dio_count;/* Number of dio_block-sized blocks */
511 	unsigned long blkmask;
512 	int create;
513 
514 	/*
515 	 * If there was a memory error and we've overwritten all the
516 	 * mapped blocks then we can now return that memory error
517 	 */
518 	ret = dio->page_errors;
519 	if (ret == 0) {
520 		map_bh->b_state = 0;
521 		map_bh->b_size = 0;
522 		BUG_ON(dio->block_in_file >= dio->final_block_in_request);
523 		fs_startblk = dio->block_in_file >> dio->blkfactor;
524 		dio_count = dio->final_block_in_request - dio->block_in_file;
525 		fs_count = dio_count >> dio->blkfactor;
526 		blkmask = (1 << dio->blkfactor) - 1;
527 		if (dio_count & blkmask)
528 			fs_count++;
529 
530 		create = dio->rw == WRITE;
531 		if (dio->lock_type == DIO_LOCKING) {
532 			if (dio->block_in_file < (i_size_read(dio->inode) >>
533 							dio->blkbits))
534 				create = 0;
535 		} else if (dio->lock_type == DIO_NO_LOCKING) {
536 			create = 0;
537 		}
538 		/*
539 		 * For writes inside i_size we forbid block creations: only
540 		 * overwrites are permitted.  We fall back to buffered writes
541 		 * at a higher level for inside-i_size block-instantiating
542 		 * writes.
543 		 */
544 		ret = (*dio->get_blocks)(dio->inode, fs_startblk, fs_count,
545 						map_bh, create);
546 	}
547 	return ret;
548 }
549 
550 /*
551  * There is no bio.  Make one now.
552  */
553 static int dio_new_bio(struct dio *dio, sector_t start_sector)
554 {
555 	sector_t sector;
556 	int ret, nr_pages;
557 
558 	ret = dio_bio_reap(dio);
559 	if (ret)
560 		goto out;
561 	sector = start_sector << (dio->blkbits - 9);
562 	nr_pages = min(dio->pages_in_io, bio_get_nr_vecs(dio->map_bh.b_bdev));
563 	BUG_ON(nr_pages <= 0);
564 	ret = dio_bio_alloc(dio, dio->map_bh.b_bdev, sector, nr_pages);
565 	dio->boundary = 0;
566 out:
567 	return ret;
568 }
569 
570 /*
571  * Attempt to put the current chunk of 'cur_page' into the current BIO.  If
572  * that was successful then update final_block_in_bio and take a ref against
573  * the just-added page.
574  *
575  * Return zero on success.  Non-zero means the caller needs to start a new BIO.
576  */
577 static int dio_bio_add_page(struct dio *dio)
578 {
579 	int ret;
580 
581 	ret = bio_add_page(dio->bio, dio->cur_page,
582 			dio->cur_page_len, dio->cur_page_offset);
583 	if (ret == dio->cur_page_len) {
584 		/*
585 		 * Decrement count only, if we are done with this page
586 		 */
587 		if ((dio->cur_page_len + dio->cur_page_offset) == PAGE_SIZE)
588 			dio->pages_in_io--;
589 		page_cache_get(dio->cur_page);
590 		dio->final_block_in_bio = dio->cur_page_block +
591 			(dio->cur_page_len >> dio->blkbits);
592 		ret = 0;
593 	} else {
594 		ret = 1;
595 	}
596 	return ret;
597 }
598 
599 /*
600  * Put cur_page under IO.  The section of cur_page which is described by
601  * cur_page_offset,cur_page_len is put into a BIO.  The section of cur_page
602  * starts on-disk at cur_page_block.
603  *
604  * We take a ref against the page here (on behalf of its presence in the bio).
605  *
606  * The caller of this function is responsible for removing cur_page from the
607  * dio, and for dropping the refcount which came from that presence.
608  */
609 static int dio_send_cur_page(struct dio *dio)
610 {
611 	int ret = 0;
612 
613 	if (dio->bio) {
614 		/*
615 		 * See whether this new request is contiguous with the old
616 		 */
617 		if (dio->final_block_in_bio != dio->cur_page_block)
618 			dio_bio_submit(dio);
619 		/*
620 		 * Submit now if the underlying fs is about to perform a
621 		 * metadata read
622 		 */
623 		if (dio->boundary)
624 			dio_bio_submit(dio);
625 	}
626 
627 	if (dio->bio == NULL) {
628 		ret = dio_new_bio(dio, dio->cur_page_block);
629 		if (ret)
630 			goto out;
631 	}
632 
633 	if (dio_bio_add_page(dio) != 0) {
634 		dio_bio_submit(dio);
635 		ret = dio_new_bio(dio, dio->cur_page_block);
636 		if (ret == 0) {
637 			ret = dio_bio_add_page(dio);
638 			BUG_ON(ret != 0);
639 		}
640 	}
641 out:
642 	return ret;
643 }
644 
645 /*
646  * An autonomous function to put a chunk of a page under deferred IO.
647  *
648  * The caller doesn't actually know (or care) whether this piece of page is in
649  * a BIO, or is under IO or whatever.  We just take care of all possible
650  * situations here.  The separation between the logic of do_direct_IO() and
651  * that of submit_page_section() is important for clarity.  Please don't break.
652  *
653  * The chunk of page starts on-disk at blocknr.
654  *
655  * We perform deferred IO, by recording the last-submitted page inside our
656  * private part of the dio structure.  If possible, we just expand the IO
657  * across that page here.
658  *
659  * If that doesn't work out then we put the old page into the bio and add this
660  * page to the dio instead.
661  */
662 static int
663 submit_page_section(struct dio *dio, struct page *page,
664 		unsigned offset, unsigned len, sector_t blocknr)
665 {
666 	int ret = 0;
667 
668 	/*
669 	 * Can we just grow the current page's presence in the dio?
670 	 */
671 	if (	(dio->cur_page == page) &&
672 		(dio->cur_page_offset + dio->cur_page_len == offset) &&
673 		(dio->cur_page_block +
674 			(dio->cur_page_len >> dio->blkbits) == blocknr)) {
675 		dio->cur_page_len += len;
676 
677 		/*
678 		 * If dio->boundary then we want to schedule the IO now to
679 		 * avoid metadata seeks.
680 		 */
681 		if (dio->boundary) {
682 			ret = dio_send_cur_page(dio);
683 			page_cache_release(dio->cur_page);
684 			dio->cur_page = NULL;
685 		}
686 		goto out;
687 	}
688 
689 	/*
690 	 * If there's a deferred page already there then send it.
691 	 */
692 	if (dio->cur_page) {
693 		ret = dio_send_cur_page(dio);
694 		page_cache_release(dio->cur_page);
695 		dio->cur_page = NULL;
696 		if (ret)
697 			goto out;
698 	}
699 
700 	page_cache_get(page);		/* It is in dio */
701 	dio->cur_page = page;
702 	dio->cur_page_offset = offset;
703 	dio->cur_page_len = len;
704 	dio->cur_page_block = blocknr;
705 out:
706 	return ret;
707 }
708 
709 /*
710  * Clean any dirty buffers in the blockdev mapping which alias newly-created
711  * file blocks.  Only called for S_ISREG files - blockdevs do not set
712  * buffer_new
713  */
714 static void clean_blockdev_aliases(struct dio *dio)
715 {
716 	unsigned i;
717 	unsigned nblocks;
718 
719 	nblocks = dio->map_bh.b_size >> dio->inode->i_blkbits;
720 
721 	for (i = 0; i < nblocks; i++) {
722 		unmap_underlying_metadata(dio->map_bh.b_bdev,
723 					dio->map_bh.b_blocknr + i);
724 	}
725 }
726 
727 /*
728  * If we are not writing the entire block and get_block() allocated
729  * the block for us, we need to fill-in the unused portion of the
730  * block with zeros. This happens only if user-buffer, fileoffset or
731  * io length is not filesystem block-size multiple.
732  *
733  * `end' is zero if we're doing the start of the IO, 1 at the end of the
734  * IO.
735  */
736 static void dio_zero_block(struct dio *dio, int end)
737 {
738 	unsigned dio_blocks_per_fs_block;
739 	unsigned this_chunk_blocks;	/* In dio_blocks */
740 	unsigned this_chunk_bytes;
741 	struct page *page;
742 
743 	dio->start_zero_done = 1;
744 	if (!dio->blkfactor || !buffer_new(&dio->map_bh))
745 		return;
746 
747 	dio_blocks_per_fs_block = 1 << dio->blkfactor;
748 	this_chunk_blocks = dio->block_in_file & (dio_blocks_per_fs_block - 1);
749 
750 	if (!this_chunk_blocks)
751 		return;
752 
753 	/*
754 	 * We need to zero out part of an fs block.  It is either at the
755 	 * beginning or the end of the fs block.
756 	 */
757 	if (end)
758 		this_chunk_blocks = dio_blocks_per_fs_block - this_chunk_blocks;
759 
760 	this_chunk_bytes = this_chunk_blocks << dio->blkbits;
761 
762 	page = ZERO_PAGE(dio->curr_user_address);
763 	if (submit_page_section(dio, page, 0, this_chunk_bytes,
764 				dio->next_block_for_io))
765 		return;
766 
767 	dio->next_block_for_io += this_chunk_blocks;
768 }
769 
770 /*
771  * Walk the user pages, and the file, mapping blocks to disk and generating
772  * a sequence of (page,offset,len,block) mappings.  These mappings are injected
773  * into submit_page_section(), which takes care of the next stage of submission
774  *
775  * Direct IO against a blockdev is different from a file.  Because we can
776  * happily perform page-sized but 512-byte aligned IOs.  It is important that
777  * blockdev IO be able to have fine alignment and large sizes.
778  *
779  * So what we do is to permit the ->get_blocks function to populate bh.b_size
780  * with the size of IO which is permitted at this offset and this i_blkbits.
781  *
782  * For best results, the blockdev should be set up with 512-byte i_blkbits and
783  * it should set b_size to PAGE_SIZE or more inside get_blocks().  This gives
784  * fine alignment but still allows this function to work in PAGE_SIZE units.
785  */
786 static int do_direct_IO(struct dio *dio)
787 {
788 	const unsigned blkbits = dio->blkbits;
789 	const unsigned blocks_per_page = PAGE_SIZE >> blkbits;
790 	struct page *page;
791 	unsigned block_in_page;
792 	struct buffer_head *map_bh = &dio->map_bh;
793 	int ret = 0;
794 
795 	/* The I/O can start at any block offset within the first page */
796 	block_in_page = dio->first_block_in_page;
797 
798 	while (dio->block_in_file < dio->final_block_in_request) {
799 		page = dio_get_page(dio);
800 		if (IS_ERR(page)) {
801 			ret = PTR_ERR(page);
802 			goto out;
803 		}
804 
805 		while (block_in_page < blocks_per_page) {
806 			unsigned offset_in_page = block_in_page << blkbits;
807 			unsigned this_chunk_bytes;	/* # of bytes mapped */
808 			unsigned this_chunk_blocks;	/* # of blocks */
809 			unsigned u;
810 
811 			if (dio->blocks_available == 0) {
812 				/*
813 				 * Need to go and map some more disk
814 				 */
815 				unsigned long blkmask;
816 				unsigned long dio_remainder;
817 
818 				ret = get_more_blocks(dio);
819 				if (ret) {
820 					page_cache_release(page);
821 					goto out;
822 				}
823 				if (!buffer_mapped(map_bh))
824 					goto do_holes;
825 
826 				dio->blocks_available =
827 						map_bh->b_size >> dio->blkbits;
828 				dio->next_block_for_io =
829 					map_bh->b_blocknr << dio->blkfactor;
830 				if (buffer_new(map_bh))
831 					clean_blockdev_aliases(dio);
832 
833 				if (!dio->blkfactor)
834 					goto do_holes;
835 
836 				blkmask = (1 << dio->blkfactor) - 1;
837 				dio_remainder = (dio->block_in_file & blkmask);
838 
839 				/*
840 				 * If we are at the start of IO and that IO
841 				 * starts partway into a fs-block,
842 				 * dio_remainder will be non-zero.  If the IO
843 				 * is a read then we can simply advance the IO
844 				 * cursor to the first block which is to be
845 				 * read.  But if the IO is a write and the
846 				 * block was newly allocated we cannot do that;
847 				 * the start of the fs block must be zeroed out
848 				 * on-disk
849 				 */
850 				if (!buffer_new(map_bh))
851 					dio->next_block_for_io += dio_remainder;
852 				dio->blocks_available -= dio_remainder;
853 			}
854 do_holes:
855 			/* Handle holes */
856 			if (!buffer_mapped(map_bh)) {
857 				char *kaddr;
858 
859 				/* AKPM: eargh, -ENOTBLK is a hack */
860 				if (dio->rw == WRITE) {
861 					page_cache_release(page);
862 					return -ENOTBLK;
863 				}
864 
865 				if (dio->block_in_file >=
866 					i_size_read(dio->inode)>>blkbits) {
867 					/* We hit eof */
868 					page_cache_release(page);
869 					goto out;
870 				}
871 				kaddr = kmap_atomic(page, KM_USER0);
872 				memset(kaddr + (block_in_page << blkbits),
873 						0, 1 << blkbits);
874 				flush_dcache_page(page);
875 				kunmap_atomic(kaddr, KM_USER0);
876 				dio->block_in_file++;
877 				block_in_page++;
878 				goto next_block;
879 			}
880 
881 			/*
882 			 * If we're performing IO which has an alignment which
883 			 * is finer than the underlying fs, go check to see if
884 			 * we must zero out the start of this block.
885 			 */
886 			if (unlikely(dio->blkfactor && !dio->start_zero_done))
887 				dio_zero_block(dio, 0);
888 
889 			/*
890 			 * Work out, in this_chunk_blocks, how much disk we
891 			 * can add to this page
892 			 */
893 			this_chunk_blocks = dio->blocks_available;
894 			u = (PAGE_SIZE - offset_in_page) >> blkbits;
895 			if (this_chunk_blocks > u)
896 				this_chunk_blocks = u;
897 			u = dio->final_block_in_request - dio->block_in_file;
898 			if (this_chunk_blocks > u)
899 				this_chunk_blocks = u;
900 			this_chunk_bytes = this_chunk_blocks << blkbits;
901 			BUG_ON(this_chunk_bytes == 0);
902 
903 			dio->boundary = buffer_boundary(map_bh);
904 			ret = submit_page_section(dio, page, offset_in_page,
905 				this_chunk_bytes, dio->next_block_for_io);
906 			if (ret) {
907 				page_cache_release(page);
908 				goto out;
909 			}
910 			dio->next_block_for_io += this_chunk_blocks;
911 
912 			dio->block_in_file += this_chunk_blocks;
913 			block_in_page += this_chunk_blocks;
914 			dio->blocks_available -= this_chunk_blocks;
915 next_block:
916 			if (dio->block_in_file > dio->final_block_in_request)
917 				BUG();
918 			if (dio->block_in_file == dio->final_block_in_request)
919 				break;
920 		}
921 
922 		/* Drop the ref which was taken in get_user_pages() */
923 		page_cache_release(page);
924 		block_in_page = 0;
925 	}
926 out:
927 	return ret;
928 }
929 
930 /*
931  * Releases both i_sem and i_alloc_sem
932  */
933 static ssize_t
934 direct_io_worker(int rw, struct kiocb *iocb, struct inode *inode,
935 	const struct iovec *iov, loff_t offset, unsigned long nr_segs,
936 	unsigned blkbits, get_blocks_t get_blocks, dio_iodone_t end_io,
937 	struct dio *dio)
938 {
939 	unsigned long user_addr;
940 	int seg;
941 	ssize_t ret = 0;
942 	ssize_t ret2;
943 	size_t bytes;
944 
945 	dio->bio = NULL;
946 	dio->inode = inode;
947 	dio->rw = rw;
948 	dio->blkbits = blkbits;
949 	dio->blkfactor = inode->i_blkbits - blkbits;
950 	dio->start_zero_done = 0;
951 	dio->size = 0;
952 	dio->block_in_file = offset >> blkbits;
953 	dio->blocks_available = 0;
954 	dio->cur_page = NULL;
955 
956 	dio->boundary = 0;
957 	dio->reap_counter = 0;
958 	dio->get_blocks = get_blocks;
959 	dio->end_io = end_io;
960 	dio->map_bh.b_private = NULL;
961 	dio->final_block_in_bio = -1;
962 	dio->next_block_for_io = -1;
963 
964 	dio->page_errors = 0;
965 	dio->result = 0;
966 	dio->iocb = iocb;
967 	dio->i_size = i_size_read(inode);
968 
969 	/*
970 	 * BIO completion state.
971 	 *
972 	 * ->bio_count starts out at one, and we decrement it to zero after all
973 	 * BIOs are submitted.  This to avoid the situation where a really fast
974 	 * (or synchronous) device could take the count to zero while we're
975 	 * still submitting BIOs.
976 	 */
977 	dio->bio_count = 1;
978 	dio->bios_in_flight = 0;
979 	spin_lock_init(&dio->bio_lock);
980 	dio->bio_list = NULL;
981 	dio->waiter = NULL;
982 
983 	/*
984 	 * In case of non-aligned buffers, we may need 2 more
985 	 * pages since we need to zero out first and last block.
986 	 */
987 	if (unlikely(dio->blkfactor))
988 		dio->pages_in_io = 2;
989 	else
990 		dio->pages_in_io = 0;
991 
992 	for (seg = 0; seg < nr_segs; seg++) {
993 		user_addr = (unsigned long)iov[seg].iov_base;
994 		dio->pages_in_io +=
995 			((user_addr+iov[seg].iov_len +PAGE_SIZE-1)/PAGE_SIZE
996 				- user_addr/PAGE_SIZE);
997 	}
998 
999 	for (seg = 0; seg < nr_segs; seg++) {
1000 		user_addr = (unsigned long)iov[seg].iov_base;
1001 		dio->size += bytes = iov[seg].iov_len;
1002 
1003 		/* Index into the first page of the first block */
1004 		dio->first_block_in_page = (user_addr & ~PAGE_MASK) >> blkbits;
1005 		dio->final_block_in_request = dio->block_in_file +
1006 						(bytes >> blkbits);
1007 		/* Page fetching state */
1008 		dio->head = 0;
1009 		dio->tail = 0;
1010 		dio->curr_page = 0;
1011 
1012 		dio->total_pages = 0;
1013 		if (user_addr & (PAGE_SIZE-1)) {
1014 			dio->total_pages++;
1015 			bytes -= PAGE_SIZE - (user_addr & (PAGE_SIZE - 1));
1016 		}
1017 		dio->total_pages += (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
1018 		dio->curr_user_address = user_addr;
1019 
1020 		ret = do_direct_IO(dio);
1021 
1022 		dio->result += iov[seg].iov_len -
1023 			((dio->final_block_in_request - dio->block_in_file) <<
1024 					blkbits);
1025 
1026 		if (ret) {
1027 			dio_cleanup(dio);
1028 			break;
1029 		}
1030 	} /* end iovec loop */
1031 
1032 	if (ret == -ENOTBLK && rw == WRITE) {
1033 		/*
1034 		 * The remaining part of the request will be
1035 		 * be handled by buffered I/O when we return
1036 		 */
1037 		ret = 0;
1038 	}
1039 	/*
1040 	 * There may be some unwritten disk at the end of a part-written
1041 	 * fs-block-sized block.  Go zero that now.
1042 	 */
1043 	dio_zero_block(dio, 1);
1044 
1045 	if (dio->cur_page) {
1046 		ret2 = dio_send_cur_page(dio);
1047 		if (ret == 0)
1048 			ret = ret2;
1049 		page_cache_release(dio->cur_page);
1050 		dio->cur_page = NULL;
1051 	}
1052 	if (dio->bio)
1053 		dio_bio_submit(dio);
1054 
1055 	/*
1056 	 * It is possible that, we return short IO due to end of file.
1057 	 * In that case, we need to release all the pages we got hold on.
1058 	 */
1059 	dio_cleanup(dio);
1060 
1061 	/*
1062 	 * All block lookups have been performed. For READ requests
1063 	 * we can let i_sem go now that its achieved its purpose
1064 	 * of protecting us from looking up uninitialized blocks.
1065 	 */
1066 	if ((rw == READ) && (dio->lock_type == DIO_LOCKING))
1067 		up(&dio->inode->i_sem);
1068 
1069 	/*
1070 	 * OK, all BIOs are submitted, so we can decrement bio_count to truly
1071 	 * reflect the number of to-be-processed BIOs.
1072 	 */
1073 	if (dio->is_async) {
1074 		int should_wait = 0;
1075 
1076 		if (dio->result < dio->size && rw == WRITE) {
1077 			dio->waiter = current;
1078 			should_wait = 1;
1079 		}
1080 		if (ret == 0)
1081 			ret = dio->result;
1082 		finished_one_bio(dio);		/* This can free the dio */
1083 		blk_run_address_space(inode->i_mapping);
1084 		if (should_wait) {
1085 			unsigned long flags;
1086 			/*
1087 			 * Wait for already issued I/O to drain out and
1088 			 * release its references to user-space pages
1089 			 * before returning to fallback on buffered I/O
1090 			 */
1091 
1092 			spin_lock_irqsave(&dio->bio_lock, flags);
1093 			set_current_state(TASK_UNINTERRUPTIBLE);
1094 			while (dio->bio_count) {
1095 				spin_unlock_irqrestore(&dio->bio_lock, flags);
1096 				io_schedule();
1097 				spin_lock_irqsave(&dio->bio_lock, flags);
1098 				set_current_state(TASK_UNINTERRUPTIBLE);
1099 			}
1100 			spin_unlock_irqrestore(&dio->bio_lock, flags);
1101 			set_current_state(TASK_RUNNING);
1102 			kfree(dio);
1103 		}
1104 	} else {
1105 		ssize_t transferred = 0;
1106 
1107 		finished_one_bio(dio);
1108 		ret2 = dio_await_completion(dio);
1109 		if (ret == 0)
1110 			ret = ret2;
1111 		if (ret == 0)
1112 			ret = dio->page_errors;
1113 		if (dio->result) {
1114 			loff_t i_size = i_size_read(inode);
1115 
1116 			transferred = dio->result;
1117 			/*
1118 			 * Adjust the return value if the read crossed a
1119 			 * non-block-aligned EOF.
1120 			 */
1121 			if (rw == READ && (offset + transferred > i_size))
1122 				transferred = i_size - offset;
1123 		}
1124 		dio_complete(dio, offset, transferred);
1125 		if (ret == 0)
1126 			ret = transferred;
1127 
1128 		/* We could have also come here on an AIO file extend */
1129 		if (!is_sync_kiocb(iocb) && rw == WRITE &&
1130 		    ret >= 0 && dio->result == dio->size)
1131 			/*
1132 			 * For AIO writes where we have completed the
1133 			 * i/o, we have to mark the the aio complete.
1134 			 */
1135 			aio_complete(iocb, ret, 0);
1136 		kfree(dio);
1137 	}
1138 	return ret;
1139 }
1140 
1141 /*
1142  * This is a library function for use by filesystem drivers.
1143  * The locking rules are governed by the dio_lock_type parameter.
1144  *
1145  * DIO_NO_LOCKING (no locking, for raw block device access)
1146  * For writes, i_sem is not held on entry; it is never taken.
1147  *
1148  * DIO_LOCKING (simple locking for regular files)
1149  * For writes we are called under i_sem and return with i_sem held, even though
1150  * it is internally dropped.
1151  * For reads, i_sem is not held on entry, but it is taken and dropped before
1152  * returning.
1153  *
1154  * DIO_OWN_LOCKING (filesystem provides synchronisation and handling of
1155  *	uninitialised data, allowing parallel direct readers and writers)
1156  * For writes we are called without i_sem, return without it, never touch it.
1157  * For reads, i_sem is held on entry and will be released before returning.
1158  *
1159  * Additional i_alloc_sem locking requirements described inline below.
1160  */
1161 ssize_t
1162 __blockdev_direct_IO(int rw, struct kiocb *iocb, struct inode *inode,
1163 	struct block_device *bdev, const struct iovec *iov, loff_t offset,
1164 	unsigned long nr_segs, get_blocks_t get_blocks, dio_iodone_t end_io,
1165 	int dio_lock_type)
1166 {
1167 	int seg;
1168 	size_t size;
1169 	unsigned long addr;
1170 	unsigned blkbits = inode->i_blkbits;
1171 	unsigned bdev_blkbits = 0;
1172 	unsigned blocksize_mask = (1 << blkbits) - 1;
1173 	ssize_t retval = -EINVAL;
1174 	loff_t end = offset;
1175 	struct dio *dio;
1176 	int reader_with_isem = (rw == READ && dio_lock_type == DIO_OWN_LOCKING);
1177 
1178 	if (rw & WRITE)
1179 		current->flags |= PF_SYNCWRITE;
1180 
1181 	if (bdev)
1182 		bdev_blkbits = blksize_bits(bdev_hardsect_size(bdev));
1183 
1184 	if (offset & blocksize_mask) {
1185 		if (bdev)
1186 			 blkbits = bdev_blkbits;
1187 		blocksize_mask = (1 << blkbits) - 1;
1188 		if (offset & blocksize_mask)
1189 			goto out;
1190 	}
1191 
1192 	/* Check the memory alignment.  Blocks cannot straddle pages */
1193 	for (seg = 0; seg < nr_segs; seg++) {
1194 		addr = (unsigned long)iov[seg].iov_base;
1195 		size = iov[seg].iov_len;
1196 		end += size;
1197 		if ((addr & blocksize_mask) || (size & blocksize_mask))  {
1198 			if (bdev)
1199 				 blkbits = bdev_blkbits;
1200 			blocksize_mask = (1 << blkbits) - 1;
1201 			if ((addr & blocksize_mask) || (size & blocksize_mask))
1202 				goto out;
1203 		}
1204 	}
1205 
1206 	dio = kmalloc(sizeof(*dio), GFP_KERNEL);
1207 	retval = -ENOMEM;
1208 	if (!dio)
1209 		goto out;
1210 
1211 	/*
1212 	 * For block device access DIO_NO_LOCKING is used,
1213 	 *	neither readers nor writers do any locking at all
1214 	 * For regular files using DIO_LOCKING,
1215 	 *	readers need to grab i_sem and i_alloc_sem
1216 	 *	writers need to grab i_alloc_sem only (i_sem is already held)
1217 	 * For regular files using DIO_OWN_LOCKING,
1218 	 *	neither readers nor writers take any locks here
1219 	 *	(i_sem is already held and release for writers here)
1220 	 */
1221 	dio->lock_type = dio_lock_type;
1222 	if (dio_lock_type != DIO_NO_LOCKING) {
1223 		/* watch out for a 0 len io from a tricksy fs */
1224 		if (rw == READ && end > offset) {
1225 			struct address_space *mapping;
1226 
1227 			mapping = iocb->ki_filp->f_mapping;
1228 			if (dio_lock_type != DIO_OWN_LOCKING) {
1229 				down(&inode->i_sem);
1230 				reader_with_isem = 1;
1231 			}
1232 
1233 			retval = filemap_write_and_wait_range(mapping, offset,
1234 							      end - 1);
1235 			if (retval) {
1236 				kfree(dio);
1237 				goto out;
1238 			}
1239 
1240 			if (dio_lock_type == DIO_OWN_LOCKING) {
1241 				up(&inode->i_sem);
1242 				reader_with_isem = 0;
1243 			}
1244 		}
1245 
1246 		if (dio_lock_type == DIO_LOCKING)
1247 			down_read(&inode->i_alloc_sem);
1248 	}
1249 
1250 	/*
1251 	 * For file extending writes updating i_size before data
1252 	 * writeouts complete can expose uninitialized blocks. So
1253 	 * even for AIO, we need to wait for i/o to complete before
1254 	 * returning in this case.
1255 	 */
1256 	dio->is_async = !is_sync_kiocb(iocb) && !((rw == WRITE) &&
1257 		(end > i_size_read(inode)));
1258 
1259 	retval = direct_io_worker(rw, iocb, inode, iov, offset,
1260 				nr_segs, blkbits, get_blocks, end_io, dio);
1261 
1262 	if (rw == READ && dio_lock_type == DIO_LOCKING)
1263 		reader_with_isem = 0;
1264 
1265 out:
1266 	if (reader_with_isem)
1267 		up(&inode->i_sem);
1268 	if (rw & WRITE)
1269 		current->flags &= ~PF_SYNCWRITE;
1270 	return retval;
1271 }
1272 EXPORT_SYMBOL(__blockdev_direct_IO);
1273