xref: /linux/fs/nfs/direct.c (revision 7db28abbea0f7dc1ec4fdfdc149db5fbd9e4c994)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * linux/fs/nfs/direct.c
4  *
5  * Copyright (C) 2003 by Chuck Lever <cel@netapp.com>
6  *
7  * High-performance uncached I/O for the Linux NFS client
8  *
9  * There are important applications whose performance or correctness
10  * depends on uncached access to file data.  Database clusters
11  * (multiple copies of the same instance running on separate hosts)
12  * implement their own cache coherency protocol that subsumes file
13  * system cache protocols.  Applications that process datasets
14  * considerably larger than the client's memory do not always benefit
15  * from a local cache.  A streaming video server, for instance, has no
16  * need to cache the contents of a file.
17  *
18  * When an application requests uncached I/O, all read and write requests
19  * are made directly to the server; data stored or fetched via these
20  * requests is not cached in the Linux page cache.  The client does not
21  * correct unaligned requests from applications.  All requested bytes are
22  * held on permanent storage before a direct write system call returns to
23  * an application.
24  *
25  * Solaris implements an uncached I/O facility called directio() that
26  * is used for backups and sequential I/O to very large files.  Solaris
27  * also supports uncaching whole NFS partitions with "-o forcedirectio,"
28  * an undocumented mount option.
29  *
30  * Designed by Jeff Kimmel, Chuck Lever, and Trond Myklebust, with
31  * help from Andrew Morton.
32  *
33  * 18 Dec 2001	Initial implementation for 2.4  --cel
34  * 08 Jul 2002	Version for 2.4.19, with bug fixes --trondmy
35  * 08 Jun 2003	Port to 2.5 APIs  --cel
36  * 31 Mar 2004	Handle direct I/O without VFS support  --cel
37  * 15 Sep 2004	Parallel async reads  --cel
38  * 04 May 2005	support O_DIRECT with aio  --cel
39  *
40  */
41 
42 #include <linux/errno.h>
43 #include <linux/sched.h>
44 #include <linux/kernel.h>
45 #include <linux/file.h>
46 #include <linux/pagemap.h>
47 #include <linux/kref.h>
48 #include <linux/slab.h>
49 #include <linux/task_io_accounting_ops.h>
50 #include <linux/module.h>
51 
52 #include <linux/nfs_fs.h>
53 #include <linux/nfs_page.h>
54 #include <linux/sunrpc/clnt.h>
55 
56 #include <linux/uaccess.h>
57 #include <linux/atomic.h>
58 
59 #include "delegation.h"
60 #include "internal.h"
61 #include "iostat.h"
62 #include "pnfs.h"
63 #include "fscache.h"
64 #include "nfstrace.h"
65 
66 #define NFSDBG_FACILITY		NFSDBG_VFS
67 
68 static struct kmem_cache *nfs_direct_cachep;
69 
70 static const struct nfs_pgio_completion_ops nfs_direct_write_completion_ops;
71 static const struct nfs_commit_completion_ops nfs_direct_commit_completion_ops;
72 static void nfs_direct_write_complete(struct nfs_direct_req *dreq);
73 static void nfs_direct_write_schedule_work(struct work_struct *work);
74 
75 static inline void get_dreq(struct nfs_direct_req *dreq)
76 {
77 	atomic_inc(&dreq->io_count);
78 }
79 
80 static inline int put_dreq(struct nfs_direct_req *dreq)
81 {
82 	return atomic_dec_and_test(&dreq->io_count);
83 }
84 
85 static void
86 nfs_direct_handle_truncated(struct nfs_direct_req *dreq,
87 			    const struct nfs_pgio_header *hdr,
88 			    ssize_t dreq_len)
89 {
90 	if (!(test_bit(NFS_IOHDR_ERROR, &hdr->flags) ||
91 	      test_bit(NFS_IOHDR_EOF, &hdr->flags)))
92 		return;
93 	if (dreq->max_count >= dreq_len) {
94 		dreq->max_count = dreq_len;
95 		if (dreq->count > dreq_len)
96 			dreq->count = dreq_len;
97 	}
98 
99 	if (test_bit(NFS_IOHDR_ERROR, &hdr->flags) && !dreq->error)
100 		dreq->error = hdr->error;
101 }
102 
103 static void
104 nfs_direct_count_bytes(struct nfs_direct_req *dreq,
105 		       const struct nfs_pgio_header *hdr)
106 {
107 	loff_t hdr_end = hdr->io_start + hdr->good_bytes;
108 	ssize_t dreq_len = 0;
109 
110 	if (hdr_end > dreq->io_start)
111 		dreq_len = hdr_end - dreq->io_start;
112 
113 	nfs_direct_handle_truncated(dreq, hdr, dreq_len);
114 
115 	if (dreq_len > dreq->max_count)
116 		dreq_len = dreq->max_count;
117 
118 	if (dreq->count < dreq_len)
119 		dreq->count = dreq_len;
120 }
121 
122 static void nfs_direct_truncate_request(struct nfs_direct_req *dreq,
123 					struct nfs_page *req)
124 {
125 	loff_t offs = req_offset(req);
126 	size_t req_start = (size_t)(offs - dreq->io_start);
127 
128 	if (req_start < dreq->max_count)
129 		dreq->max_count = req_start;
130 	if (req_start < dreq->count)
131 		dreq->count = req_start;
132 }
133 
134 static void nfs_direct_file_adjust_size_locked(struct inode *inode,
135 					       loff_t offset, size_t count)
136 {
137 	loff_t newsize = offset + (loff_t)count;
138 	loff_t oldsize = i_size_read(inode);
139 
140 	if (newsize > oldsize) {
141 		i_size_write(inode, newsize);
142 		NFS_I(inode)->cache_validity &= ~NFS_INO_INVALID_SIZE;
143 		trace_nfs_size_grow(inode, newsize);
144 		nfs_inc_stats(inode, NFSIOS_EXTENDWRITE);
145 	}
146 }
147 
148 static void nfs_direct_release_pages(struct page **pages, unsigned int npages)
149 {
150 	unsigned int i;
151 	for (i = 0; i < npages; i++)
152 		put_page(pages[i]);
153 }
154 
155 void nfs_init_cinfo_from_dreq(struct nfs_commit_info *cinfo,
156 			      struct nfs_direct_req *dreq)
157 {
158 	cinfo->inode = dreq->inode;
159 	cinfo->mds = &dreq->mds_cinfo;
160 	cinfo->ds = &dreq->ds_cinfo;
161 	cinfo->dreq = dreq;
162 	cinfo->completion_ops = &nfs_direct_commit_completion_ops;
163 }
164 
165 static inline struct nfs_direct_req *nfs_direct_req_alloc(void)
166 {
167 	struct nfs_direct_req *dreq;
168 
169 	dreq = kmem_cache_zalloc(nfs_direct_cachep, GFP_KERNEL);
170 	if (!dreq)
171 		return NULL;
172 
173 	kref_init(&dreq->kref);
174 	kref_get(&dreq->kref);
175 	init_completion(&dreq->completion);
176 	INIT_LIST_HEAD(&dreq->mds_cinfo.list);
177 	pnfs_init_ds_commit_info(&dreq->ds_cinfo);
178 	INIT_WORK(&dreq->work, nfs_direct_write_schedule_work);
179 	spin_lock_init(&dreq->lock);
180 
181 	return dreq;
182 }
183 
184 static void nfs_direct_req_free(struct kref *kref)
185 {
186 	struct nfs_direct_req *dreq = container_of(kref, struct nfs_direct_req, kref);
187 
188 	pnfs_release_ds_info(&dreq->ds_cinfo, dreq->inode);
189 	if (dreq->l_ctx != NULL)
190 		nfs_put_lock_context(dreq->l_ctx);
191 	if (dreq->ctx != NULL)
192 		put_nfs_open_context(dreq->ctx);
193 	kmem_cache_free(nfs_direct_cachep, dreq);
194 }
195 
196 static void nfs_direct_req_release(struct nfs_direct_req *dreq)
197 {
198 	kref_put(&dreq->kref, nfs_direct_req_free);
199 }
200 
201 ssize_t nfs_dreq_bytes_left(struct nfs_direct_req *dreq, loff_t offset)
202 {
203 	loff_t start = offset - dreq->io_start;
204 	return dreq->max_count - start;
205 }
206 EXPORT_SYMBOL_GPL(nfs_dreq_bytes_left);
207 
208 /*
209  * Collects and returns the final error value/byte-count.
210  */
211 static ssize_t nfs_direct_wait(struct nfs_direct_req *dreq)
212 {
213 	ssize_t result = -EIOCBQUEUED;
214 
215 	/* Async requests don't wait here */
216 	if (dreq->iocb)
217 		goto out;
218 
219 	result = wait_for_completion_killable(&dreq->completion);
220 
221 	if (!result) {
222 		result = dreq->count;
223 		WARN_ON_ONCE(dreq->count < 0);
224 	}
225 	if (!result)
226 		result = dreq->error;
227 
228 out:
229 	return (ssize_t) result;
230 }
231 
232 /*
233  * Synchronous I/O uses a stack-allocated iocb.  Thus we can't trust
234  * the iocb is still valid here if this is a synchronous request.
235  */
236 static void nfs_direct_complete(struct nfs_direct_req *dreq)
237 {
238 	struct inode *inode = dreq->inode;
239 
240 	inode_dio_end(inode);
241 
242 	if (dreq->iocb) {
243 		long res = (long) dreq->error;
244 		if (dreq->count != 0) {
245 			res = (long) dreq->count;
246 			WARN_ON_ONCE(dreq->count < 0);
247 		}
248 		dreq->iocb->ki_complete(dreq->iocb, res);
249 	}
250 
251 	complete(&dreq->completion);
252 
253 	nfs_direct_req_release(dreq);
254 }
255 
256 static void nfs_direct_read_completion(struct nfs_pgio_header *hdr)
257 {
258 	unsigned long bytes = 0;
259 	struct nfs_direct_req *dreq = hdr->dreq;
260 
261 	spin_lock(&dreq->lock);
262 	if (test_bit(NFS_IOHDR_REDO, &hdr->flags)) {
263 		spin_unlock(&dreq->lock);
264 		goto out_put;
265 	}
266 
267 	nfs_direct_count_bytes(dreq, hdr);
268 	spin_unlock(&dreq->lock);
269 
270 	nfs_update_delegated_atime(dreq->inode);
271 
272 	while (!list_empty(&hdr->pages)) {
273 		struct nfs_page *req = nfs_list_entry(hdr->pages.next);
274 		struct page *page = req->wb_page;
275 
276 		if (!PageCompound(page) && bytes < hdr->good_bytes &&
277 		    (dreq->flags == NFS_ODIRECT_SHOULD_DIRTY))
278 			set_page_dirty(page);
279 		bytes += req->wb_bytes;
280 		nfs_list_remove_request(req);
281 		nfs_release_request(req);
282 	}
283 out_put:
284 	if (put_dreq(dreq))
285 		nfs_direct_complete(dreq);
286 	hdr->release(hdr);
287 }
288 
289 static void nfs_read_sync_pgio_error(struct list_head *head, int error)
290 {
291 	struct nfs_page *req;
292 
293 	while (!list_empty(head)) {
294 		req = nfs_list_entry(head->next);
295 		nfs_list_remove_request(req);
296 		nfs_release_request(req);
297 	}
298 }
299 
300 static void nfs_direct_pgio_init(struct nfs_pgio_header *hdr)
301 {
302 	get_dreq(hdr->dreq);
303 	set_bit(NFS_IOHDR_ODIRECT, &hdr->flags);
304 }
305 
306 static const struct nfs_pgio_completion_ops nfs_direct_read_completion_ops = {
307 	.error_cleanup = nfs_read_sync_pgio_error,
308 	.init_hdr = nfs_direct_pgio_init,
309 	.completion = nfs_direct_read_completion,
310 };
311 
312 /*
313  * For each rsize'd chunk of the user's buffer, dispatch an NFS READ
314  * operation.  If nfs_readdata_alloc() or get_user_pages() fails,
315  * bail and stop sending more reads.  Read length accounting is
316  * handled automatically by nfs_direct_read_result().  Otherwise, if
317  * no requests have been sent, just return an error.
318  */
319 
320 static ssize_t nfs_direct_read_schedule_iovec(struct nfs_direct_req *dreq,
321 					      struct iov_iter *iter,
322 					      loff_t pos)
323 {
324 	struct nfs_pageio_descriptor desc;
325 	struct inode *inode = dreq->inode;
326 	ssize_t result = -EINVAL;
327 	size_t requested_bytes = 0;
328 	size_t rsize = max_t(size_t, NFS_SERVER(inode)->rsize, PAGE_SIZE);
329 
330 	nfs_pageio_init_read(&desc, dreq->inode, false,
331 			     &nfs_direct_read_completion_ops);
332 	get_dreq(dreq);
333 	desc.pg_dreq = dreq;
334 	inode_dio_begin(inode);
335 
336 	while (iov_iter_count(iter)) {
337 		struct page **pagevec;
338 		size_t bytes;
339 		size_t pgbase;
340 		unsigned npages, i;
341 
342 		result = iov_iter_get_pages_alloc2(iter, &pagevec,
343 						  rsize, &pgbase);
344 		if (result < 0)
345 			break;
346 
347 		bytes = result;
348 		npages = (result + pgbase + PAGE_SIZE - 1) / PAGE_SIZE;
349 		for (i = 0; i < npages; i++) {
350 			struct nfs_page *req;
351 			unsigned int req_len = min_t(size_t, bytes, PAGE_SIZE - pgbase);
352 			/* XXX do we need to do the eof zeroing found in async_filler? */
353 			req = nfs_page_create_from_page(dreq->ctx, pagevec[i],
354 							pgbase, pos, req_len);
355 			if (IS_ERR(req)) {
356 				result = PTR_ERR(req);
357 				break;
358 			}
359 			if (!nfs_pageio_add_request(&desc, req)) {
360 				result = desc.pg_error;
361 				nfs_release_request(req);
362 				break;
363 			}
364 			pgbase = 0;
365 			bytes -= req_len;
366 			requested_bytes += req_len;
367 			pos += req_len;
368 		}
369 		nfs_direct_release_pages(pagevec, npages);
370 		kvfree(pagevec);
371 		if (result < 0)
372 			break;
373 	}
374 
375 	nfs_pageio_complete(&desc);
376 
377 	/*
378 	 * If no bytes were started, return the error, and let the
379 	 * generic layer handle the completion.
380 	 */
381 	if (requested_bytes == 0) {
382 		inode_dio_end(inode);
383 		nfs_direct_req_release(dreq);
384 		return result < 0 ? result : -EIO;
385 	}
386 
387 	if (put_dreq(dreq))
388 		nfs_direct_complete(dreq);
389 	return requested_bytes;
390 }
391 
392 /**
393  * nfs_file_direct_read - file direct read operation for NFS files
394  * @iocb: target I/O control block
395  * @iter: vector of user buffers into which to read data
396  * @swap: flag indicating this is swap IO, not O_DIRECT IO
397  *
398  * We use this function for direct reads instead of calling
399  * generic_file_aio_read() in order to avoid gfar's check to see if
400  * the request starts before the end of the file.  For that check
401  * to work, we must generate a GETATTR before each direct read, and
402  * even then there is a window between the GETATTR and the subsequent
403  * READ where the file size could change.  Our preference is simply
404  * to do all reads the application wants, and the server will take
405  * care of managing the end of file boundary.
406  *
407  * This function also eliminates unnecessarily updating the file's
408  * atime locally, as the NFS server sets the file's atime, and this
409  * client must read the updated atime from the server back into its
410  * cache.
411  */
412 ssize_t nfs_file_direct_read(struct kiocb *iocb, struct iov_iter *iter,
413 			     bool swap)
414 {
415 	struct file *file = iocb->ki_filp;
416 	struct address_space *mapping = file->f_mapping;
417 	struct inode *inode = mapping->host;
418 	struct nfs_direct_req *dreq;
419 	struct nfs_lock_context *l_ctx;
420 	ssize_t result, requested;
421 	size_t count = iov_iter_count(iter);
422 	nfs_add_stats(mapping->host, NFSIOS_DIRECTREADBYTES, count);
423 
424 	dfprintk(FILE, "NFS: direct read(%pD2, %zd@%Ld)\n",
425 		file, count, (long long) iocb->ki_pos);
426 
427 	result = 0;
428 	if (!count)
429 		goto out;
430 
431 	task_io_account_read(count);
432 
433 	result = -ENOMEM;
434 	dreq = nfs_direct_req_alloc();
435 	if (dreq == NULL)
436 		goto out;
437 
438 	dreq->inode = inode;
439 	dreq->max_count = count;
440 	dreq->io_start = iocb->ki_pos;
441 	dreq->ctx = get_nfs_open_context(nfs_file_open_context(iocb->ki_filp));
442 	l_ctx = nfs_get_lock_context(dreq->ctx);
443 	if (IS_ERR(l_ctx)) {
444 		result = PTR_ERR(l_ctx);
445 		nfs_direct_req_release(dreq);
446 		goto out_release;
447 	}
448 	dreq->l_ctx = l_ctx;
449 	if (!is_sync_kiocb(iocb)) {
450 		dreq->iocb = iocb;
451 	} else if (iocb->ki_flags & IOCB_NOWAIT) {
452 		result = -EAGAIN;
453 		nfs_direct_req_release(dreq);
454 		goto out_release;
455 	}
456 
457 	if (user_backed_iter(iter))
458 		dreq->flags = NFS_ODIRECT_SHOULD_DIRTY;
459 
460 	if (!swap) {
461 		if (iocb->ki_flags & IOCB_NOWAIT)
462 			result = nfs_start_io_direct_nowait(inode);
463 		else
464 			result = nfs_start_io_direct(inode);
465 		if (result) {
466 			/* release the reference that would usually be
467 			 * consumed by nfs_direct_read_schedule_iovec()
468 			 */
469 			nfs_direct_req_release(dreq);
470 			goto out_release;
471 		}
472 	}
473 
474 	NFS_I(inode)->read_io += count;
475 	requested = nfs_direct_read_schedule_iovec(dreq, iter, iocb->ki_pos);
476 
477 	if (!swap)
478 		nfs_end_io_direct(inode);
479 
480 	if (requested > 0) {
481 		result = nfs_direct_wait(dreq);
482 		if (result > 0) {
483 			requested -= result;
484 			iocb->ki_pos += result;
485 		}
486 		iov_iter_revert(iter, requested);
487 	} else {
488 		result = requested;
489 	}
490 
491 out_release:
492 	nfs_direct_req_release(dreq);
493 out:
494 	return result;
495 }
496 
497 static void nfs_direct_add_page_head(struct list_head *list,
498 				     struct nfs_page *req)
499 {
500 	struct nfs_page *head = req->wb_head;
501 
502 	if (!list_empty(&head->wb_list) || !nfs_lock_request(head))
503 		return;
504 	if (!list_empty(&head->wb_list)) {
505 		nfs_unlock_request(head);
506 		return;
507 	}
508 	list_add(&head->wb_list, list);
509 	kref_get(&head->wb_kref);
510 	kref_get(&head->wb_kref);
511 }
512 
513 static void nfs_direct_join_group(struct list_head *list,
514 				  struct nfs_commit_info *cinfo,
515 				  struct inode *inode)
516 {
517 	struct nfs_page *req, *subreq;
518 
519 	list_for_each_entry(req, list, wb_list) {
520 		if (req->wb_head != req) {
521 			nfs_direct_add_page_head(&req->wb_list, req);
522 			continue;
523 		}
524 		subreq = req->wb_this_page;
525 		if (subreq == req)
526 			continue;
527 		do {
528 			/*
529 			 * Remove subrequests from this list before freeing
530 			 * them in the call to nfs_join_page_group().
531 			 */
532 			if (!list_empty(&subreq->wb_list)) {
533 				nfs_list_remove_request(subreq);
534 				nfs_release_request(subreq);
535 			}
536 		} while ((subreq = subreq->wb_this_page) != req);
537 		nfs_join_page_group(req, cinfo, inode);
538 	}
539 }
540 
541 static void
542 nfs_direct_write_scan_commit_list(struct inode *inode,
543 				  struct list_head *list,
544 				  struct nfs_commit_info *cinfo)
545 {
546 	mutex_lock(&NFS_I(cinfo->inode)->commit_mutex);
547 	pnfs_recover_commit_reqs(list, cinfo);
548 	nfs_scan_commit_list(&cinfo->mds->list, list, cinfo, 0);
549 	mutex_unlock(&NFS_I(cinfo->inode)->commit_mutex);
550 }
551 
552 static void nfs_direct_write_reschedule(struct nfs_direct_req *dreq)
553 {
554 	struct nfs_pageio_descriptor desc;
555 	struct nfs_page *req;
556 	LIST_HEAD(reqs);
557 	struct nfs_commit_info cinfo;
558 
559 	nfs_init_cinfo_from_dreq(&cinfo, dreq);
560 	nfs_direct_write_scan_commit_list(dreq->inode, &reqs, &cinfo);
561 
562 	nfs_direct_join_group(&reqs, &cinfo, dreq->inode);
563 
564 	nfs_clear_pnfs_ds_commit_verifiers(&dreq->ds_cinfo);
565 	get_dreq(dreq);
566 
567 	nfs_pageio_init_write(&desc, dreq->inode, FLUSH_STABLE, false,
568 			      &nfs_direct_write_completion_ops);
569 	desc.pg_dreq = dreq;
570 
571 	while (!list_empty(&reqs)) {
572 		req = nfs_list_entry(reqs.next);
573 		/* Bump the transmission count */
574 		req->wb_nio++;
575 		if (!nfs_pageio_add_request(&desc, req)) {
576 			spin_lock(&dreq->lock);
577 			if (dreq->error < 0) {
578 				desc.pg_error = dreq->error;
579 			} else if (desc.pg_error != -EAGAIN) {
580 				dreq->flags = 0;
581 				if (!desc.pg_error)
582 					desc.pg_error = -EIO;
583 				dreq->error = desc.pg_error;
584 			} else
585 				dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
586 			spin_unlock(&dreq->lock);
587 			break;
588 		}
589 		nfs_release_request(req);
590 	}
591 	nfs_pageio_complete(&desc);
592 
593 	while (!list_empty(&reqs)) {
594 		req = nfs_list_entry(reqs.next);
595 		nfs_list_remove_request(req);
596 		nfs_unlock_and_release_request(req);
597 		if (desc.pg_error == -EAGAIN) {
598 			nfs_mark_request_commit(req, NULL, &cinfo, 0);
599 		} else {
600 			spin_lock(&dreq->lock);
601 			nfs_direct_truncate_request(dreq, req);
602 			spin_unlock(&dreq->lock);
603 			nfs_release_request(req);
604 		}
605 	}
606 
607 	if (put_dreq(dreq))
608 		nfs_direct_write_complete(dreq);
609 }
610 
611 static void nfs_direct_commit_complete(struct nfs_commit_data *data)
612 {
613 	const struct nfs_writeverf *verf = data->res.verf;
614 	struct nfs_direct_req *dreq = data->dreq;
615 	struct nfs_commit_info cinfo;
616 	struct nfs_page *req;
617 	int status = data->task.tk_status;
618 
619 	trace_nfs_direct_commit_complete(dreq);
620 
621 	spin_lock(&dreq->lock);
622 	if (status < 0) {
623 		/* Errors in commit are fatal */
624 		dreq->error = status;
625 		dreq->flags = NFS_ODIRECT_DONE;
626 	} else {
627 		status = dreq->error;
628 	}
629 	spin_unlock(&dreq->lock);
630 
631 	nfs_init_cinfo_from_dreq(&cinfo, dreq);
632 
633 	while (!list_empty(&data->pages)) {
634 		req = nfs_list_entry(data->pages.next);
635 		nfs_list_remove_request(req);
636 		if (status < 0) {
637 			spin_lock(&dreq->lock);
638 			nfs_direct_truncate_request(dreq, req);
639 			spin_unlock(&dreq->lock);
640 			nfs_release_request(req);
641 		} else if (!nfs_write_match_verf(verf, req)) {
642 			spin_lock(&dreq->lock);
643 			if (dreq->flags == 0)
644 				dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
645 			spin_unlock(&dreq->lock);
646 			/*
647 			 * Despite the reboot, the write was successful,
648 			 * so reset wb_nio.
649 			 */
650 			req->wb_nio = 0;
651 			nfs_mark_request_commit(req, NULL, &cinfo, 0);
652 		} else
653 			nfs_release_request(req);
654 		nfs_unlock_and_release_request(req);
655 	}
656 
657 	if (nfs_commit_end(cinfo.mds))
658 		nfs_direct_write_complete(dreq);
659 }
660 
661 static void nfs_direct_resched_write(struct nfs_commit_info *cinfo,
662 		struct nfs_page *req)
663 {
664 	struct nfs_direct_req *dreq = cinfo->dreq;
665 
666 	trace_nfs_direct_resched_write(dreq);
667 
668 	spin_lock(&dreq->lock);
669 	if (dreq->flags != NFS_ODIRECT_DONE)
670 		dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
671 	spin_unlock(&dreq->lock);
672 	nfs_mark_request_commit(req, NULL, cinfo, 0);
673 }
674 
675 static const struct nfs_commit_completion_ops nfs_direct_commit_completion_ops = {
676 	.completion = nfs_direct_commit_complete,
677 	.resched_write = nfs_direct_resched_write,
678 };
679 
680 static void nfs_direct_commit_schedule(struct nfs_direct_req *dreq)
681 {
682 	int res;
683 	struct nfs_commit_info cinfo;
684 	LIST_HEAD(mds_list);
685 
686 	nfs_init_cinfo_from_dreq(&cinfo, dreq);
687 	nfs_commit_begin(cinfo.mds);
688 	nfs_scan_commit(dreq->inode, &mds_list, &cinfo);
689 	res = nfs_generic_commit_list(dreq->inode, &mds_list, 0, &cinfo);
690 	if (res < 0) { /* res == -ENOMEM */
691 		spin_lock(&dreq->lock);
692 		if (dreq->flags == 0)
693 			dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
694 		spin_unlock(&dreq->lock);
695 	}
696 	if (nfs_commit_end(cinfo.mds))
697 		nfs_direct_write_complete(dreq);
698 }
699 
700 static void nfs_direct_write_clear_reqs(struct nfs_direct_req *dreq)
701 {
702 	struct nfs_commit_info cinfo;
703 	struct nfs_page *req;
704 	LIST_HEAD(reqs);
705 
706 	nfs_init_cinfo_from_dreq(&cinfo, dreq);
707 	nfs_direct_write_scan_commit_list(dreq->inode, &reqs, &cinfo);
708 
709 	while (!list_empty(&reqs)) {
710 		req = nfs_list_entry(reqs.next);
711 		nfs_list_remove_request(req);
712 		nfs_direct_truncate_request(dreq, req);
713 		nfs_release_request(req);
714 		nfs_unlock_and_release_request(req);
715 	}
716 }
717 
718 static void nfs_direct_write_schedule_work(struct work_struct *work)
719 {
720 	struct nfs_direct_req *dreq = container_of(work, struct nfs_direct_req, work);
721 	int flags = dreq->flags;
722 
723 	dreq->flags = 0;
724 	switch (flags) {
725 		case NFS_ODIRECT_DO_COMMIT:
726 			nfs_direct_commit_schedule(dreq);
727 			break;
728 		case NFS_ODIRECT_RESCHED_WRITES:
729 			nfs_direct_write_reschedule(dreq);
730 			break;
731 		default:
732 			nfs_direct_write_clear_reqs(dreq);
733 			nfs_zap_mapping(dreq->inode, dreq->inode->i_mapping);
734 			nfs_direct_complete(dreq);
735 	}
736 }
737 
738 static void nfs_direct_write_complete(struct nfs_direct_req *dreq)
739 {
740 	trace_nfs_direct_write_complete(dreq);
741 	queue_work(nfsiod_workqueue, &dreq->work); /* Calls nfs_direct_write_schedule_work */
742 }
743 
744 static void nfs_direct_write_completion(struct nfs_pgio_header *hdr)
745 {
746 	struct nfs_direct_req *dreq = hdr->dreq;
747 	struct nfs_commit_info cinfo;
748 	struct inode *inode = dreq->inode;
749 	int flags = NFS_ODIRECT_DONE;
750 
751 	trace_nfs_direct_write_completion(dreq);
752 
753 	nfs_init_cinfo_from_dreq(&cinfo, dreq);
754 
755 	spin_lock(&dreq->lock);
756 	if (test_bit(NFS_IOHDR_REDO, &hdr->flags)) {
757 		spin_unlock(&dreq->lock);
758 		goto out_put;
759 	}
760 
761 	nfs_direct_count_bytes(dreq, hdr);
762 	if (test_bit(NFS_IOHDR_UNSTABLE_WRITES, &hdr->flags) &&
763 	    !test_bit(NFS_IOHDR_ERROR, &hdr->flags)) {
764 		if (!dreq->flags)
765 			dreq->flags = NFS_ODIRECT_DO_COMMIT;
766 		flags = dreq->flags;
767 	}
768 	spin_unlock(&dreq->lock);
769 
770 	spin_lock(&inode->i_lock);
771 	nfs_direct_file_adjust_size_locked(inode, dreq->io_start, dreq->count);
772 	nfs_update_delegated_mtime_locked(dreq->inode);
773 	spin_unlock(&inode->i_lock);
774 
775 	while (!list_empty(&hdr->pages)) {
776 		struct nfs_page *req;
777 
778 		req = nfs_list_entry(hdr->pages.next);
779 		nfs_list_remove_request(req);
780 		if (flags == NFS_ODIRECT_DO_COMMIT) {
781 			kref_get(&req->wb_kref);
782 			memcpy(&req->wb_verf, &hdr->verf.verifier,
783 			       sizeof(req->wb_verf));
784 			nfs_mark_request_commit(req, hdr->lseg, &cinfo,
785 				hdr->ds_commit_idx);
786 		} else if (flags == NFS_ODIRECT_RESCHED_WRITES) {
787 			kref_get(&req->wb_kref);
788 			nfs_mark_request_commit(req, NULL, &cinfo, 0);
789 		}
790 		nfs_unlock_and_release_request(req);
791 	}
792 
793 out_put:
794 	if (put_dreq(dreq))
795 		nfs_direct_write_complete(dreq);
796 	hdr->release(hdr);
797 }
798 
799 static void nfs_write_sync_pgio_error(struct list_head *head, int error)
800 {
801 	struct nfs_page *req;
802 
803 	while (!list_empty(head)) {
804 		req = nfs_list_entry(head->next);
805 		nfs_list_remove_request(req);
806 		nfs_unlock_and_release_request(req);
807 	}
808 }
809 
810 static void nfs_direct_write_reschedule_io(struct nfs_pgio_header *hdr)
811 {
812 	struct nfs_direct_req *dreq = hdr->dreq;
813 	struct nfs_page *req;
814 	struct nfs_commit_info cinfo;
815 
816 	trace_nfs_direct_write_reschedule_io(dreq);
817 
818 	nfs_init_cinfo_from_dreq(&cinfo, dreq);
819 	spin_lock(&dreq->lock);
820 	if (dreq->error == 0)
821 		dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
822 	set_bit(NFS_IOHDR_REDO, &hdr->flags);
823 	spin_unlock(&dreq->lock);
824 	while (!list_empty(&hdr->pages)) {
825 		req = nfs_list_entry(hdr->pages.next);
826 		nfs_list_remove_request(req);
827 		nfs_unlock_request(req);
828 		nfs_mark_request_commit(req, NULL, &cinfo, 0);
829 	}
830 }
831 
832 static const struct nfs_pgio_completion_ops nfs_direct_write_completion_ops = {
833 	.error_cleanup = nfs_write_sync_pgio_error,
834 	.init_hdr = nfs_direct_pgio_init,
835 	.completion = nfs_direct_write_completion,
836 	.reschedule_io = nfs_direct_write_reschedule_io,
837 };
838 
839 
840 /*
841  * NB: Return the value of the first error return code.  Subsequent
842  *     errors after the first one are ignored.
843  */
844 /*
845  * For each wsize'd chunk of the user's buffer, dispatch an NFS WRITE
846  * operation.  If nfs_writedata_alloc() or get_user_pages() fails,
847  * bail and stop sending more writes.  Write length accounting is
848  * handled automatically by nfs_direct_write_result().  Otherwise, if
849  * no requests have been sent, just return an error.
850  */
851 static ssize_t nfs_direct_write_schedule_iovec(struct nfs_direct_req *dreq,
852 					       struct iov_iter *iter,
853 					       loff_t pos, int ioflags)
854 {
855 	struct nfs_pageio_descriptor desc;
856 	struct inode *inode = dreq->inode;
857 	struct nfs_commit_info cinfo;
858 	ssize_t result = 0;
859 	size_t requested_bytes = 0;
860 	size_t wsize = max_t(size_t, NFS_SERVER(inode)->wsize, PAGE_SIZE);
861 	bool defer = false;
862 
863 	trace_nfs_direct_write_schedule_iovec(dreq);
864 
865 	nfs_pageio_init_write(&desc, inode, ioflags, false,
866 			      &nfs_direct_write_completion_ops);
867 	desc.pg_dreq = dreq;
868 	get_dreq(dreq);
869 	inode_dio_begin(inode);
870 
871 	NFS_I(inode)->write_io += iov_iter_count(iter);
872 	while (iov_iter_count(iter)) {
873 		struct page **pagevec;
874 		size_t bytes;
875 		size_t pgbase;
876 		unsigned npages, i;
877 
878 		result = iov_iter_get_pages_alloc2(iter, &pagevec,
879 						  wsize, &pgbase);
880 		if (result < 0)
881 			break;
882 
883 		bytes = result;
884 		npages = (result + pgbase + PAGE_SIZE - 1) / PAGE_SIZE;
885 		for (i = 0; i < npages; i++) {
886 			struct nfs_page *req;
887 			unsigned int req_len = min_t(size_t, bytes, PAGE_SIZE - pgbase);
888 
889 			req = nfs_page_create_from_page(dreq->ctx, pagevec[i],
890 							pgbase, pos, req_len);
891 			if (IS_ERR(req)) {
892 				result = PTR_ERR(req);
893 				break;
894 			}
895 
896 			if (desc.pg_error < 0) {
897 				nfs_free_request(req);
898 				result = desc.pg_error;
899 				break;
900 			}
901 
902 			pgbase = 0;
903 			bytes -= req_len;
904 			requested_bytes += req_len;
905 			pos += req_len;
906 
907 			if (defer) {
908 				nfs_mark_request_commit(req, NULL, &cinfo, 0);
909 				continue;
910 			}
911 
912 			nfs_lock_request(req);
913 			if (nfs_pageio_add_request(&desc, req))
914 				continue;
915 
916 			/* Exit on hard errors */
917 			if (desc.pg_error < 0 && desc.pg_error != -EAGAIN) {
918 				result = desc.pg_error;
919 				nfs_unlock_and_release_request(req);
920 				break;
921 			}
922 
923 			/* If the error is soft, defer remaining requests */
924 			nfs_init_cinfo_from_dreq(&cinfo, dreq);
925 			spin_lock(&dreq->lock);
926 			dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
927 			spin_unlock(&dreq->lock);
928 			nfs_unlock_request(req);
929 			nfs_mark_request_commit(req, NULL, &cinfo, 0);
930 			desc.pg_error = 0;
931 			defer = true;
932 		}
933 		nfs_direct_release_pages(pagevec, npages);
934 		kvfree(pagevec);
935 		if (result < 0)
936 			break;
937 	}
938 	nfs_pageio_complete(&desc);
939 
940 	/*
941 	 * If no bytes were started, return the error, and let the
942 	 * generic layer handle the completion.
943 	 */
944 	if (requested_bytes == 0) {
945 		inode_dio_end(inode);
946 		nfs_direct_req_release(dreq);
947 		return result < 0 ? result : -EIO;
948 	}
949 
950 	if (put_dreq(dreq))
951 		nfs_direct_write_complete(dreq);
952 	return requested_bytes;
953 }
954 
955 /**
956  * nfs_file_direct_write - file direct write operation for NFS files
957  * @iocb: target I/O control block
958  * @iter: vector of user buffers from which to write data
959  * @swap: flag indicating this is swap IO, not O_DIRECT IO
960  *
961  * We use this function for direct writes instead of calling
962  * generic_file_aio_write() in order to avoid taking the inode
963  * semaphore and updating the i_size.  The NFS server will set
964  * the new i_size and this client must read the updated size
965  * back into its cache.  We let the server do generic write
966  * parameter checking and report problems.
967  *
968  * We eliminate local atime updates, see direct read above.
969  *
970  * We avoid unnecessary page cache invalidations for normal cached
971  * readers of this file.
972  *
973  * Note that O_APPEND is not supported for NFS direct writes, as there
974  * is no atomic O_APPEND write facility in the NFS protocol.
975  */
976 ssize_t nfs_file_direct_write(struct kiocb *iocb, struct iov_iter *iter,
977 			      bool swap)
978 {
979 	ssize_t result, requested;
980 	size_t count;
981 	struct file *file = iocb->ki_filp;
982 	struct address_space *mapping = file->f_mapping;
983 	struct inode *inode = mapping->host;
984 	struct nfs_direct_req *dreq;
985 	struct nfs_lock_context *l_ctx;
986 	loff_t pos, end;
987 
988 	dfprintk(FILE, "NFS: direct write(%pD2, %zd@%Ld)\n",
989 		file, iov_iter_count(iter), (long long) iocb->ki_pos);
990 
991 	if (swap)
992 		/* bypass generic checks */
993 		result =  iov_iter_count(iter);
994 	else
995 		result = generic_write_checks(iocb, iter);
996 	if (result <= 0)
997 		return result;
998 	count = result;
999 	nfs_add_stats(mapping->host, NFSIOS_DIRECTWRITTENBYTES, count);
1000 
1001 	pos = iocb->ki_pos;
1002 	end = (pos + iov_iter_count(iter) - 1) >> PAGE_SHIFT;
1003 
1004 	task_io_account_write(count);
1005 
1006 	result = -ENOMEM;
1007 	dreq = nfs_direct_req_alloc();
1008 	if (!dreq)
1009 		goto out;
1010 
1011 	dreq->inode = inode;
1012 	dreq->max_count = count;
1013 	dreq->io_start = pos;
1014 	dreq->ctx = get_nfs_open_context(nfs_file_open_context(iocb->ki_filp));
1015 	l_ctx = nfs_get_lock_context(dreq->ctx);
1016 	if (IS_ERR(l_ctx)) {
1017 		result = PTR_ERR(l_ctx);
1018 		nfs_direct_req_release(dreq);
1019 		goto out_release;
1020 	}
1021 	dreq->l_ctx = l_ctx;
1022 	if (!is_sync_kiocb(iocb))
1023 		dreq->iocb = iocb;
1024 	pnfs_init_ds_commit_info_ops(&dreq->ds_cinfo, inode);
1025 
1026 	if (swap) {
1027 		requested = nfs_direct_write_schedule_iovec(dreq, iter, pos,
1028 							    FLUSH_STABLE);
1029 	} else {
1030 		result = nfs_start_io_direct(inode);
1031 		if (result) {
1032 			/* release the reference that would usually be
1033 			 * consumed by nfs_direct_write_schedule_iovec()
1034 			 */
1035 			nfs_direct_req_release(dreq);
1036 			goto out_release;
1037 		}
1038 
1039 		requested = nfs_direct_write_schedule_iovec(dreq, iter, pos,
1040 							    FLUSH_COND_STABLE);
1041 
1042 		if (mapping->nrpages) {
1043 			invalidate_inode_pages2_range(mapping,
1044 						      pos >> PAGE_SHIFT, end);
1045 		}
1046 
1047 		nfs_end_io_direct(inode);
1048 	}
1049 
1050 	if (requested > 0) {
1051 		result = nfs_direct_wait(dreq);
1052 		if (result > 0) {
1053 			requested -= result;
1054 			iocb->ki_pos = pos + result;
1055 			/* XXX: should check the generic_write_sync retval */
1056 			generic_write_sync(iocb, result);
1057 		}
1058 		iov_iter_revert(iter, requested);
1059 	} else {
1060 		result = requested;
1061 	}
1062 	nfs_fscache_invalidate(inode, FSCACHE_INVAL_DIO_WRITE);
1063 out_release:
1064 	nfs_direct_req_release(dreq);
1065 out:
1066 	return result;
1067 }
1068 
1069 /**
1070  * nfs_init_directcache - create a slab cache for nfs_direct_req structures
1071  *
1072  */
1073 int __init nfs_init_directcache(void)
1074 {
1075 	nfs_direct_cachep = kmem_cache_create("nfs_direct_cache",
1076 						sizeof(struct nfs_direct_req),
1077 						0, SLAB_RECLAIM_ACCOUNT,
1078 						NULL);
1079 	if (nfs_direct_cachep == NULL)
1080 		return -ENOMEM;
1081 
1082 	return 0;
1083 }
1084 
1085 /**
1086  * nfs_destroy_directcache - destroy the slab cache for nfs_direct_req structures
1087  *
1088  */
1089 void nfs_destroy_directcache(void)
1090 {
1091 	kmem_cache_destroy(nfs_direct_cachep);
1092 }
1093