xref: /openbmc/linux/fs/nfs/direct.c (revision 18f412969687ded8f1debd21da758b041993e974)
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 "internal.h"
60 #include "iostat.h"
61 #include "pnfs.h"
62 
63 #define NFSDBG_FACILITY		NFSDBG_VFS
64 
65 static struct kmem_cache *nfs_direct_cachep;
66 
67 struct nfs_direct_req {
68 	struct kref		kref;		/* release manager */
69 
70 	/* I/O parameters */
71 	struct nfs_open_context	*ctx;		/* file open context info */
72 	struct nfs_lock_context *l_ctx;		/* Lock context info */
73 	struct kiocb *		iocb;		/* controlling i/o request */
74 	struct inode *		inode;		/* target file of i/o */
75 
76 	/* completion state */
77 	atomic_t		io_count;	/* i/os we're waiting for */
78 	spinlock_t		lock;		/* protect completion state */
79 
80 	loff_t			io_start;	/* Start offset for I/O */
81 	ssize_t			count,		/* bytes actually processed */
82 				max_count,	/* max expected count */
83 				bytes_left,	/* bytes left to be sent */
84 				error;		/* any reported error */
85 	struct completion	completion;	/* wait for i/o completion */
86 
87 	/* commit state */
88 	struct nfs_mds_commit_info mds_cinfo;	/* Storage for cinfo */
89 	struct pnfs_ds_commit_info ds_cinfo;	/* Storage for cinfo */
90 	struct work_struct	work;
91 	int			flags;
92 	/* for write */
93 #define NFS_ODIRECT_DO_COMMIT		(1)	/* an unstable reply was received */
94 #define NFS_ODIRECT_RESCHED_WRITES	(2)	/* write verification failed */
95 	/* for read */
96 #define NFS_ODIRECT_SHOULD_DIRTY	(3)	/* dirty user-space page after read */
97 	struct nfs_writeverf	verf;		/* unstable write verifier */
98 };
99 
100 static const struct nfs_pgio_completion_ops nfs_direct_write_completion_ops;
101 static const struct nfs_commit_completion_ops nfs_direct_commit_completion_ops;
102 static void nfs_direct_write_complete(struct nfs_direct_req *dreq);
103 static void nfs_direct_write_schedule_work(struct work_struct *work);
104 
105 static inline void get_dreq(struct nfs_direct_req *dreq)
106 {
107 	atomic_inc(&dreq->io_count);
108 }
109 
110 static inline int put_dreq(struct nfs_direct_req *dreq)
111 {
112 	return atomic_dec_and_test(&dreq->io_count);
113 }
114 
115 static void
116 nfs_direct_handle_truncated(struct nfs_direct_req *dreq,
117 			    const struct nfs_pgio_header *hdr,
118 			    ssize_t dreq_len)
119 {
120 	if (!(test_bit(NFS_IOHDR_ERROR, &hdr->flags) ||
121 	      test_bit(NFS_IOHDR_EOF, &hdr->flags)))
122 		return;
123 	if (dreq->max_count >= dreq_len) {
124 		dreq->max_count = dreq_len;
125 		if (dreq->count > dreq_len)
126 			dreq->count = dreq_len;
127 
128 		if (test_bit(NFS_IOHDR_ERROR, &hdr->flags))
129 			dreq->error = hdr->error;
130 		else /* Clear outstanding error if this is EOF */
131 			dreq->error = 0;
132 	}
133 }
134 
135 static void
136 nfs_direct_count_bytes(struct nfs_direct_req *dreq,
137 		       const struct nfs_pgio_header *hdr)
138 {
139 	loff_t hdr_end = hdr->io_start + hdr->good_bytes;
140 	ssize_t dreq_len = 0;
141 
142 	if (hdr_end > dreq->io_start)
143 		dreq_len = hdr_end - dreq->io_start;
144 
145 	nfs_direct_handle_truncated(dreq, hdr, dreq_len);
146 
147 	if (dreq_len > dreq->max_count)
148 		dreq_len = dreq->max_count;
149 
150 	if (dreq->count < dreq_len)
151 		dreq->count = dreq_len;
152 }
153 
154 /*
155  * nfs_direct_select_verf - select the right verifier
156  * @dreq - direct request possibly spanning multiple servers
157  * @ds_clp - nfs_client of data server or NULL if MDS / non-pnfs
158  * @commit_idx - commit bucket index for the DS
159  *
160  * returns the correct verifier to use given the role of the server
161  */
162 static struct nfs_writeverf *
163 nfs_direct_select_verf(struct nfs_direct_req *dreq,
164 		       struct nfs_client *ds_clp,
165 		       int commit_idx)
166 {
167 	struct nfs_writeverf *verfp = &dreq->verf;
168 
169 #ifdef CONFIG_NFS_V4_1
170 	/*
171 	 * pNFS is in use, use the DS verf except commit_through_mds is set
172 	 * for layout segment where nbuckets is zero.
173 	 */
174 	if (ds_clp && dreq->ds_cinfo.nbuckets > 0) {
175 		if (commit_idx >= 0 && commit_idx < dreq->ds_cinfo.nbuckets)
176 			verfp = &dreq->ds_cinfo.buckets[commit_idx].direct_verf;
177 		else
178 			WARN_ON_ONCE(1);
179 	}
180 #endif
181 	return verfp;
182 }
183 
184 
185 /*
186  * nfs_direct_set_hdr_verf - set the write/commit verifier
187  * @dreq - direct request possibly spanning multiple servers
188  * @hdr - pageio header to validate against previously seen verfs
189  *
190  * Set the server's (MDS or DS) "seen" verifier
191  */
192 static void nfs_direct_set_hdr_verf(struct nfs_direct_req *dreq,
193 				    struct nfs_pgio_header *hdr)
194 {
195 	struct nfs_writeverf *verfp;
196 
197 	verfp = nfs_direct_select_verf(dreq, hdr->ds_clp, hdr->ds_commit_idx);
198 	WARN_ON_ONCE(verfp->committed >= 0);
199 	memcpy(verfp, &hdr->verf, sizeof(struct nfs_writeverf));
200 	WARN_ON_ONCE(verfp->committed < 0);
201 }
202 
203 static int nfs_direct_cmp_verf(const struct nfs_writeverf *v1,
204 		const struct nfs_writeverf *v2)
205 {
206 	return nfs_write_verifier_cmp(&v1->verifier, &v2->verifier);
207 }
208 
209 /*
210  * nfs_direct_cmp_hdr_verf - compare verifier for pgio header
211  * @dreq - direct request possibly spanning multiple servers
212  * @hdr - pageio header to validate against previously seen verf
213  *
214  * set the server's "seen" verf if not initialized.
215  * returns result of comparison between @hdr->verf and the "seen"
216  * verf of the server used by @hdr (DS or MDS)
217  */
218 static int nfs_direct_set_or_cmp_hdr_verf(struct nfs_direct_req *dreq,
219 					  struct nfs_pgio_header *hdr)
220 {
221 	struct nfs_writeverf *verfp;
222 
223 	verfp = nfs_direct_select_verf(dreq, hdr->ds_clp, hdr->ds_commit_idx);
224 	if (verfp->committed < 0) {
225 		nfs_direct_set_hdr_verf(dreq, hdr);
226 		return 0;
227 	}
228 	return nfs_direct_cmp_verf(verfp, &hdr->verf);
229 }
230 
231 /*
232  * nfs_direct_cmp_commit_data_verf - compare verifier for commit data
233  * @dreq - direct request possibly spanning multiple servers
234  * @data - commit data to validate against previously seen verf
235  *
236  * returns result of comparison between @data->verf and the verf of
237  * the server used by @data (DS or MDS)
238  */
239 static int nfs_direct_cmp_commit_data_verf(struct nfs_direct_req *dreq,
240 					   struct nfs_commit_data *data)
241 {
242 	struct nfs_writeverf *verfp;
243 
244 	verfp = nfs_direct_select_verf(dreq, data->ds_clp,
245 					 data->ds_commit_index);
246 
247 	/* verifier not set so always fail */
248 	if (verfp->committed < 0 || data->res.verf->committed <= NFS_UNSTABLE)
249 		return 1;
250 
251 	return nfs_direct_cmp_verf(verfp, data->res.verf);
252 }
253 
254 /**
255  * nfs_direct_IO - NFS address space operation for direct I/O
256  * @iocb: target I/O control block
257  * @iter: I/O buffer
258  *
259  * The presence of this routine in the address space ops vector means
260  * the NFS client supports direct I/O. However, for most direct IO, we
261  * shunt off direct read and write requests before the VFS gets them,
262  * so this method is only ever called for swap.
263  */
264 ssize_t nfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
265 {
266 	struct inode *inode = iocb->ki_filp->f_mapping->host;
267 
268 	/* we only support swap file calling nfs_direct_IO */
269 	if (!IS_SWAPFILE(inode))
270 		return 0;
271 
272 	VM_BUG_ON(iov_iter_count(iter) != PAGE_SIZE);
273 
274 	if (iov_iter_rw(iter) == READ)
275 		return nfs_file_direct_read(iocb, iter);
276 	return nfs_file_direct_write(iocb, iter);
277 }
278 
279 static void nfs_direct_release_pages(struct page **pages, unsigned int npages)
280 {
281 	unsigned int i;
282 	for (i = 0; i < npages; i++)
283 		put_page(pages[i]);
284 }
285 
286 void nfs_init_cinfo_from_dreq(struct nfs_commit_info *cinfo,
287 			      struct nfs_direct_req *dreq)
288 {
289 	cinfo->inode = dreq->inode;
290 	cinfo->mds = &dreq->mds_cinfo;
291 	cinfo->ds = &dreq->ds_cinfo;
292 	cinfo->dreq = dreq;
293 	cinfo->completion_ops = &nfs_direct_commit_completion_ops;
294 }
295 
296 static inline struct nfs_direct_req *nfs_direct_req_alloc(void)
297 {
298 	struct nfs_direct_req *dreq;
299 
300 	dreq = kmem_cache_zalloc(nfs_direct_cachep, GFP_KERNEL);
301 	if (!dreq)
302 		return NULL;
303 
304 	kref_init(&dreq->kref);
305 	kref_get(&dreq->kref);
306 	init_completion(&dreq->completion);
307 	INIT_LIST_HEAD(&dreq->mds_cinfo.list);
308 	pnfs_init_ds_commit_info(&dreq->ds_cinfo);
309 	dreq->verf.committed = NFS_INVALID_STABLE_HOW;	/* not set yet */
310 	INIT_WORK(&dreq->work, nfs_direct_write_schedule_work);
311 	spin_lock_init(&dreq->lock);
312 
313 	return dreq;
314 }
315 
316 static void nfs_direct_req_free(struct kref *kref)
317 {
318 	struct nfs_direct_req *dreq = container_of(kref, struct nfs_direct_req, kref);
319 
320 	pnfs_release_ds_info(&dreq->ds_cinfo, dreq->inode);
321 	nfs_free_pnfs_ds_cinfo(&dreq->ds_cinfo);
322 	if (dreq->l_ctx != NULL)
323 		nfs_put_lock_context(dreq->l_ctx);
324 	if (dreq->ctx != NULL)
325 		put_nfs_open_context(dreq->ctx);
326 	kmem_cache_free(nfs_direct_cachep, dreq);
327 }
328 
329 static void nfs_direct_req_release(struct nfs_direct_req *dreq)
330 {
331 	kref_put(&dreq->kref, nfs_direct_req_free);
332 }
333 
334 ssize_t nfs_dreq_bytes_left(struct nfs_direct_req *dreq)
335 {
336 	return dreq->bytes_left;
337 }
338 EXPORT_SYMBOL_GPL(nfs_dreq_bytes_left);
339 
340 /*
341  * Collects and returns the final error value/byte-count.
342  */
343 static ssize_t nfs_direct_wait(struct nfs_direct_req *dreq)
344 {
345 	ssize_t result = -EIOCBQUEUED;
346 
347 	/* Async requests don't wait here */
348 	if (dreq->iocb)
349 		goto out;
350 
351 	result = wait_for_completion_killable(&dreq->completion);
352 
353 	if (!result) {
354 		result = dreq->count;
355 		WARN_ON_ONCE(dreq->count < 0);
356 	}
357 	if (!result)
358 		result = dreq->error;
359 
360 out:
361 	return (ssize_t) result;
362 }
363 
364 /*
365  * Synchronous I/O uses a stack-allocated iocb.  Thus we can't trust
366  * the iocb is still valid here if this is a synchronous request.
367  */
368 static void nfs_direct_complete(struct nfs_direct_req *dreq)
369 {
370 	struct inode *inode = dreq->inode;
371 
372 	inode_dio_end(inode);
373 
374 	if (dreq->iocb) {
375 		long res = (long) dreq->error;
376 		if (dreq->count != 0) {
377 			res = (long) dreq->count;
378 			WARN_ON_ONCE(dreq->count < 0);
379 		}
380 		dreq->iocb->ki_complete(dreq->iocb, res, 0);
381 	}
382 
383 	complete(&dreq->completion);
384 
385 	nfs_direct_req_release(dreq);
386 }
387 
388 static void nfs_direct_read_completion(struct nfs_pgio_header *hdr)
389 {
390 	unsigned long bytes = 0;
391 	struct nfs_direct_req *dreq = hdr->dreq;
392 
393 	spin_lock(&dreq->lock);
394 	if (test_bit(NFS_IOHDR_REDO, &hdr->flags)) {
395 		spin_unlock(&dreq->lock);
396 		goto out_put;
397 	}
398 
399 	nfs_direct_count_bytes(dreq, hdr);
400 	spin_unlock(&dreq->lock);
401 
402 	while (!list_empty(&hdr->pages)) {
403 		struct nfs_page *req = nfs_list_entry(hdr->pages.next);
404 		struct page *page = req->wb_page;
405 
406 		if (!PageCompound(page) && bytes < hdr->good_bytes &&
407 		    (dreq->flags == NFS_ODIRECT_SHOULD_DIRTY))
408 			set_page_dirty(page);
409 		bytes += req->wb_bytes;
410 		nfs_list_remove_request(req);
411 		nfs_release_request(req);
412 	}
413 out_put:
414 	if (put_dreq(dreq))
415 		nfs_direct_complete(dreq);
416 	hdr->release(hdr);
417 }
418 
419 static void nfs_read_sync_pgio_error(struct list_head *head, int error)
420 {
421 	struct nfs_page *req;
422 
423 	while (!list_empty(head)) {
424 		req = nfs_list_entry(head->next);
425 		nfs_list_remove_request(req);
426 		nfs_release_request(req);
427 	}
428 }
429 
430 static void nfs_direct_pgio_init(struct nfs_pgio_header *hdr)
431 {
432 	get_dreq(hdr->dreq);
433 }
434 
435 static const struct nfs_pgio_completion_ops nfs_direct_read_completion_ops = {
436 	.error_cleanup = nfs_read_sync_pgio_error,
437 	.init_hdr = nfs_direct_pgio_init,
438 	.completion = nfs_direct_read_completion,
439 };
440 
441 /*
442  * For each rsize'd chunk of the user's buffer, dispatch an NFS READ
443  * operation.  If nfs_readdata_alloc() or get_user_pages() fails,
444  * bail and stop sending more reads.  Read length accounting is
445  * handled automatically by nfs_direct_read_result().  Otherwise, if
446  * no requests have been sent, just return an error.
447  */
448 
449 static ssize_t nfs_direct_read_schedule_iovec(struct nfs_direct_req *dreq,
450 					      struct iov_iter *iter,
451 					      loff_t pos)
452 {
453 	struct nfs_pageio_descriptor desc;
454 	struct inode *inode = dreq->inode;
455 	ssize_t result = -EINVAL;
456 	size_t requested_bytes = 0;
457 	size_t rsize = max_t(size_t, NFS_SERVER(inode)->rsize, PAGE_SIZE);
458 
459 	nfs_pageio_init_read(&desc, dreq->inode, false,
460 			     &nfs_direct_read_completion_ops);
461 	get_dreq(dreq);
462 	desc.pg_dreq = dreq;
463 	inode_dio_begin(inode);
464 
465 	while (iov_iter_count(iter)) {
466 		struct page **pagevec;
467 		size_t bytes;
468 		size_t pgbase;
469 		unsigned npages, i;
470 
471 		result = iov_iter_get_pages_alloc(iter, &pagevec,
472 						  rsize, &pgbase);
473 		if (result < 0)
474 			break;
475 
476 		bytes = result;
477 		iov_iter_advance(iter, bytes);
478 		npages = (result + pgbase + PAGE_SIZE - 1) / PAGE_SIZE;
479 		for (i = 0; i < npages; i++) {
480 			struct nfs_page *req;
481 			unsigned int req_len = min_t(size_t, bytes, PAGE_SIZE - pgbase);
482 			/* XXX do we need to do the eof zeroing found in async_filler? */
483 			req = nfs_create_request(dreq->ctx, pagevec[i],
484 						 pgbase, req_len);
485 			if (IS_ERR(req)) {
486 				result = PTR_ERR(req);
487 				break;
488 			}
489 			req->wb_index = pos >> PAGE_SHIFT;
490 			req->wb_offset = pos & ~PAGE_MASK;
491 			if (!nfs_pageio_add_request(&desc, req)) {
492 				result = desc.pg_error;
493 				nfs_release_request(req);
494 				break;
495 			}
496 			pgbase = 0;
497 			bytes -= req_len;
498 			requested_bytes += req_len;
499 			pos += req_len;
500 			dreq->bytes_left -= req_len;
501 		}
502 		nfs_direct_release_pages(pagevec, npages);
503 		kvfree(pagevec);
504 		if (result < 0)
505 			break;
506 	}
507 
508 	nfs_pageio_complete(&desc);
509 
510 	/*
511 	 * If no bytes were started, return the error, and let the
512 	 * generic layer handle the completion.
513 	 */
514 	if (requested_bytes == 0) {
515 		inode_dio_end(inode);
516 		nfs_direct_req_release(dreq);
517 		return result < 0 ? result : -EIO;
518 	}
519 
520 	if (put_dreq(dreq))
521 		nfs_direct_complete(dreq);
522 	return requested_bytes;
523 }
524 
525 /**
526  * nfs_file_direct_read - file direct read operation for NFS files
527  * @iocb: target I/O control block
528  * @iter: vector of user buffers into which to read data
529  *
530  * We use this function for direct reads instead of calling
531  * generic_file_aio_read() in order to avoid gfar's check to see if
532  * the request starts before the end of the file.  For that check
533  * to work, we must generate a GETATTR before each direct read, and
534  * even then there is a window between the GETATTR and the subsequent
535  * READ where the file size could change.  Our preference is simply
536  * to do all reads the application wants, and the server will take
537  * care of managing the end of file boundary.
538  *
539  * This function also eliminates unnecessarily updating the file's
540  * atime locally, as the NFS server sets the file's atime, and this
541  * client must read the updated atime from the server back into its
542  * cache.
543  */
544 ssize_t nfs_file_direct_read(struct kiocb *iocb, struct iov_iter *iter)
545 {
546 	struct file *file = iocb->ki_filp;
547 	struct address_space *mapping = file->f_mapping;
548 	struct inode *inode = mapping->host;
549 	struct nfs_direct_req *dreq;
550 	struct nfs_lock_context *l_ctx;
551 	ssize_t result = -EINVAL, requested;
552 	size_t count = iov_iter_count(iter);
553 	nfs_add_stats(mapping->host, NFSIOS_DIRECTREADBYTES, count);
554 
555 	dfprintk(FILE, "NFS: direct read(%pD2, %zd@%Ld)\n",
556 		file, count, (long long) iocb->ki_pos);
557 
558 	result = 0;
559 	if (!count)
560 		goto out;
561 
562 	task_io_account_read(count);
563 
564 	result = -ENOMEM;
565 	dreq = nfs_direct_req_alloc();
566 	if (dreq == NULL)
567 		goto out;
568 
569 	dreq->inode = inode;
570 	dreq->bytes_left = dreq->max_count = count;
571 	dreq->io_start = iocb->ki_pos;
572 	dreq->ctx = get_nfs_open_context(nfs_file_open_context(iocb->ki_filp));
573 	l_ctx = nfs_get_lock_context(dreq->ctx);
574 	if (IS_ERR(l_ctx)) {
575 		result = PTR_ERR(l_ctx);
576 		nfs_direct_req_release(dreq);
577 		goto out_release;
578 	}
579 	dreq->l_ctx = l_ctx;
580 	if (!is_sync_kiocb(iocb))
581 		dreq->iocb = iocb;
582 
583 	if (iter_is_iovec(iter))
584 		dreq->flags = NFS_ODIRECT_SHOULD_DIRTY;
585 
586 	nfs_start_io_direct(inode);
587 
588 	NFS_I(inode)->read_io += count;
589 	requested = nfs_direct_read_schedule_iovec(dreq, iter, iocb->ki_pos);
590 
591 	nfs_end_io_direct(inode);
592 
593 	if (requested > 0) {
594 		result = nfs_direct_wait(dreq);
595 		if (result > 0) {
596 			requested -= result;
597 			iocb->ki_pos += result;
598 		}
599 		iov_iter_revert(iter, requested);
600 	} else {
601 		result = requested;
602 	}
603 
604 out_release:
605 	nfs_direct_req_release(dreq);
606 out:
607 	return result;
608 }
609 
610 static void
611 nfs_direct_write_scan_commit_list(struct inode *inode,
612 				  struct list_head *list,
613 				  struct nfs_commit_info *cinfo)
614 {
615 	mutex_lock(&NFS_I(cinfo->inode)->commit_mutex);
616 #ifdef CONFIG_NFS_V4_1
617 	if (cinfo->ds != NULL && cinfo->ds->nwritten != 0)
618 		NFS_SERVER(inode)->pnfs_curr_ld->recover_commit_reqs(list, cinfo);
619 #endif
620 	nfs_scan_commit_list(&cinfo->mds->list, list, cinfo, 0);
621 	mutex_unlock(&NFS_I(cinfo->inode)->commit_mutex);
622 }
623 
624 static void nfs_direct_write_reschedule(struct nfs_direct_req *dreq)
625 {
626 	struct nfs_pageio_descriptor desc;
627 	struct nfs_page *req, *tmp;
628 	LIST_HEAD(reqs);
629 	struct nfs_commit_info cinfo;
630 	LIST_HEAD(failed);
631 
632 	nfs_init_cinfo_from_dreq(&cinfo, dreq);
633 	nfs_direct_write_scan_commit_list(dreq->inode, &reqs, &cinfo);
634 
635 	dreq->count = 0;
636 	dreq->max_count = 0;
637 	list_for_each_entry(req, &reqs, wb_list)
638 		dreq->max_count += req->wb_bytes;
639 	dreq->verf.committed = NFS_INVALID_STABLE_HOW;
640 	nfs_clear_pnfs_ds_commit_verifiers(&dreq->ds_cinfo);
641 	get_dreq(dreq);
642 
643 	nfs_pageio_init_write(&desc, dreq->inode, FLUSH_STABLE, false,
644 			      &nfs_direct_write_completion_ops);
645 	desc.pg_dreq = dreq;
646 
647 	list_for_each_entry_safe(req, tmp, &reqs, wb_list) {
648 		/* Bump the transmission count */
649 		req->wb_nio++;
650 		if (!nfs_pageio_add_request(&desc, req)) {
651 			nfs_list_move_request(req, &failed);
652 			spin_lock(&cinfo.inode->i_lock);
653 			dreq->flags = 0;
654 			if (desc.pg_error < 0)
655 				dreq->error = desc.pg_error;
656 			else
657 				dreq->error = -EIO;
658 			spin_unlock(&cinfo.inode->i_lock);
659 		}
660 		nfs_release_request(req);
661 	}
662 	nfs_pageio_complete(&desc);
663 
664 	while (!list_empty(&failed)) {
665 		req = nfs_list_entry(failed.next);
666 		nfs_list_remove_request(req);
667 		nfs_unlock_and_release_request(req);
668 	}
669 
670 	if (put_dreq(dreq))
671 		nfs_direct_write_complete(dreq);
672 }
673 
674 static void nfs_direct_commit_complete(struct nfs_commit_data *data)
675 {
676 	struct nfs_direct_req *dreq = data->dreq;
677 	struct nfs_commit_info cinfo;
678 	struct nfs_page *req;
679 	int status = data->task.tk_status;
680 
681 	nfs_init_cinfo_from_dreq(&cinfo, dreq);
682 	if (status < 0 || nfs_direct_cmp_commit_data_verf(dreq, data))
683 		dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
684 
685 	while (!list_empty(&data->pages)) {
686 		req = nfs_list_entry(data->pages.next);
687 		nfs_list_remove_request(req);
688 		if (dreq->flags == NFS_ODIRECT_RESCHED_WRITES) {
689 			/*
690 			 * Despite the reboot, the write was successful,
691 			 * so reset wb_nio.
692 			 */
693 			req->wb_nio = 0;
694 			/* Note the rewrite will go through mds */
695 			nfs_mark_request_commit(req, NULL, &cinfo, 0);
696 		} else
697 			nfs_release_request(req);
698 		nfs_unlock_and_release_request(req);
699 	}
700 
701 	if (atomic_dec_and_test(&cinfo.mds->rpcs_out))
702 		nfs_direct_write_complete(dreq);
703 }
704 
705 static void nfs_direct_resched_write(struct nfs_commit_info *cinfo,
706 		struct nfs_page *req)
707 {
708 	struct nfs_direct_req *dreq = cinfo->dreq;
709 
710 	spin_lock(&dreq->lock);
711 	dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
712 	spin_unlock(&dreq->lock);
713 	nfs_mark_request_commit(req, NULL, cinfo, 0);
714 }
715 
716 static const struct nfs_commit_completion_ops nfs_direct_commit_completion_ops = {
717 	.completion = nfs_direct_commit_complete,
718 	.resched_write = nfs_direct_resched_write,
719 };
720 
721 static void nfs_direct_commit_schedule(struct nfs_direct_req *dreq)
722 {
723 	int res;
724 	struct nfs_commit_info cinfo;
725 	LIST_HEAD(mds_list);
726 
727 	nfs_init_cinfo_from_dreq(&cinfo, dreq);
728 	nfs_scan_commit(dreq->inode, &mds_list, &cinfo);
729 	res = nfs_generic_commit_list(dreq->inode, &mds_list, 0, &cinfo);
730 	if (res < 0) /* res == -ENOMEM */
731 		nfs_direct_write_reschedule(dreq);
732 }
733 
734 static void nfs_direct_write_schedule_work(struct work_struct *work)
735 {
736 	struct nfs_direct_req *dreq = container_of(work, struct nfs_direct_req, work);
737 	int flags = dreq->flags;
738 
739 	dreq->flags = 0;
740 	switch (flags) {
741 		case NFS_ODIRECT_DO_COMMIT:
742 			nfs_direct_commit_schedule(dreq);
743 			break;
744 		case NFS_ODIRECT_RESCHED_WRITES:
745 			nfs_direct_write_reschedule(dreq);
746 			break;
747 		default:
748 			nfs_zap_mapping(dreq->inode, dreq->inode->i_mapping);
749 			nfs_direct_complete(dreq);
750 	}
751 }
752 
753 static void nfs_direct_write_complete(struct nfs_direct_req *dreq)
754 {
755 	queue_work(nfsiod_workqueue, &dreq->work); /* Calls nfs_direct_write_schedule_work */
756 }
757 
758 static void nfs_direct_write_completion(struct nfs_pgio_header *hdr)
759 {
760 	struct nfs_direct_req *dreq = hdr->dreq;
761 	struct nfs_commit_info cinfo;
762 	bool request_commit = false;
763 	struct nfs_page *req = nfs_list_entry(hdr->pages.next);
764 
765 	nfs_init_cinfo_from_dreq(&cinfo, dreq);
766 
767 	spin_lock(&dreq->lock);
768 	if (test_bit(NFS_IOHDR_REDO, &hdr->flags)) {
769 		spin_unlock(&dreq->lock);
770 		goto out_put;
771 	}
772 
773 	nfs_direct_count_bytes(dreq, hdr);
774 	if (hdr->good_bytes != 0) {
775 		if (nfs_write_need_commit(hdr)) {
776 			if (dreq->flags == NFS_ODIRECT_RESCHED_WRITES)
777 				request_commit = true;
778 			else if (dreq->flags == 0) {
779 				nfs_direct_set_hdr_verf(dreq, hdr);
780 				request_commit = true;
781 				dreq->flags = NFS_ODIRECT_DO_COMMIT;
782 			} else if (dreq->flags == NFS_ODIRECT_DO_COMMIT) {
783 				request_commit = true;
784 				if (nfs_direct_set_or_cmp_hdr_verf(dreq, hdr))
785 					dreq->flags =
786 						NFS_ODIRECT_RESCHED_WRITES;
787 			}
788 		}
789 	}
790 	spin_unlock(&dreq->lock);
791 
792 	while (!list_empty(&hdr->pages)) {
793 
794 		req = nfs_list_entry(hdr->pages.next);
795 		nfs_list_remove_request(req);
796 		if (request_commit) {
797 			kref_get(&req->wb_kref);
798 			nfs_mark_request_commit(req, hdr->lseg, &cinfo,
799 				hdr->ds_commit_idx);
800 		}
801 		nfs_unlock_and_release_request(req);
802 	}
803 
804 out_put:
805 	if (put_dreq(dreq))
806 		nfs_direct_write_complete(dreq);
807 	hdr->release(hdr);
808 }
809 
810 static void nfs_write_sync_pgio_error(struct list_head *head, int error)
811 {
812 	struct nfs_page *req;
813 
814 	while (!list_empty(head)) {
815 		req = nfs_list_entry(head->next);
816 		nfs_list_remove_request(req);
817 		nfs_unlock_and_release_request(req);
818 	}
819 }
820 
821 static void nfs_direct_write_reschedule_io(struct nfs_pgio_header *hdr)
822 {
823 	struct nfs_direct_req *dreq = hdr->dreq;
824 
825 	spin_lock(&dreq->lock);
826 	if (dreq->error == 0) {
827 		dreq->flags = NFS_ODIRECT_RESCHED_WRITES;
828 		/* fake unstable write to let common nfs resend pages */
829 		hdr->verf.committed = NFS_UNSTABLE;
830 		hdr->good_bytes = hdr->args.offset + hdr->args.count -
831 			hdr->io_start;
832 	}
833 	spin_unlock(&dreq->lock);
834 }
835 
836 static const struct nfs_pgio_completion_ops nfs_direct_write_completion_ops = {
837 	.error_cleanup = nfs_write_sync_pgio_error,
838 	.init_hdr = nfs_direct_pgio_init,
839 	.completion = nfs_direct_write_completion,
840 	.reschedule_io = nfs_direct_write_reschedule_io,
841 };
842 
843 
844 /*
845  * NB: Return the value of the first error return code.  Subsequent
846  *     errors after the first one are ignored.
847  */
848 /*
849  * For each wsize'd chunk of the user's buffer, dispatch an NFS WRITE
850  * operation.  If nfs_writedata_alloc() or get_user_pages() fails,
851  * bail and stop sending more writes.  Write length accounting is
852  * handled automatically by nfs_direct_write_result().  Otherwise, if
853  * no requests have been sent, just return an error.
854  */
855 static ssize_t nfs_direct_write_schedule_iovec(struct nfs_direct_req *dreq,
856 					       struct iov_iter *iter,
857 					       loff_t pos)
858 {
859 	struct nfs_pageio_descriptor desc;
860 	struct inode *inode = dreq->inode;
861 	ssize_t result = 0;
862 	size_t requested_bytes = 0;
863 	size_t wsize = max_t(size_t, NFS_SERVER(inode)->wsize, PAGE_SIZE);
864 
865 	nfs_pageio_init_write(&desc, inode, FLUSH_COND_STABLE, 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_alloc(iter, &pagevec,
879 						  wsize, &pgbase);
880 		if (result < 0)
881 			break;
882 
883 		bytes = result;
884 		iov_iter_advance(iter, bytes);
885 		npages = (result + pgbase + PAGE_SIZE - 1) / PAGE_SIZE;
886 		for (i = 0; i < npages; i++) {
887 			struct nfs_page *req;
888 			unsigned int req_len = min_t(size_t, bytes, PAGE_SIZE - pgbase);
889 
890 			req = nfs_create_request(dreq->ctx, pagevec[i],
891 						 pgbase, req_len);
892 			if (IS_ERR(req)) {
893 				result = PTR_ERR(req);
894 				break;
895 			}
896 
897 			if (desc.pg_error < 0) {
898 				nfs_free_request(req);
899 				result = desc.pg_error;
900 				break;
901 			}
902 
903 			nfs_lock_request(req);
904 			req->wb_index = pos >> PAGE_SHIFT;
905 			req->wb_offset = pos & ~PAGE_MASK;
906 			if (!nfs_pageio_add_request(&desc, req)) {
907 				result = desc.pg_error;
908 				nfs_unlock_and_release_request(req);
909 				break;
910 			}
911 			pgbase = 0;
912 			bytes -= req_len;
913 			requested_bytes += req_len;
914 			pos += req_len;
915 			dreq->bytes_left -= req_len;
916 		}
917 		nfs_direct_release_pages(pagevec, npages);
918 		kvfree(pagevec);
919 		if (result < 0)
920 			break;
921 	}
922 	nfs_pageio_complete(&desc);
923 
924 	/*
925 	 * If no bytes were started, return the error, and let the
926 	 * generic layer handle the completion.
927 	 */
928 	if (requested_bytes == 0) {
929 		inode_dio_end(inode);
930 		nfs_direct_req_release(dreq);
931 		return result < 0 ? result : -EIO;
932 	}
933 
934 	if (put_dreq(dreq))
935 		nfs_direct_write_complete(dreq);
936 	return requested_bytes;
937 }
938 
939 /**
940  * nfs_file_direct_write - file direct write operation for NFS files
941  * @iocb: target I/O control block
942  * @iter: vector of user buffers from which to write data
943  *
944  * We use this function for direct writes instead of calling
945  * generic_file_aio_write() in order to avoid taking the inode
946  * semaphore and updating the i_size.  The NFS server will set
947  * the new i_size and this client must read the updated size
948  * back into its cache.  We let the server do generic write
949  * parameter checking and report problems.
950  *
951  * We eliminate local atime updates, see direct read above.
952  *
953  * We avoid unnecessary page cache invalidations for normal cached
954  * readers of this file.
955  *
956  * Note that O_APPEND is not supported for NFS direct writes, as there
957  * is no atomic O_APPEND write facility in the NFS protocol.
958  */
959 ssize_t nfs_file_direct_write(struct kiocb *iocb, struct iov_iter *iter)
960 {
961 	ssize_t result = -EINVAL, requested;
962 	size_t count;
963 	struct file *file = iocb->ki_filp;
964 	struct address_space *mapping = file->f_mapping;
965 	struct inode *inode = mapping->host;
966 	struct nfs_direct_req *dreq;
967 	struct nfs_lock_context *l_ctx;
968 	loff_t pos, end;
969 
970 	dfprintk(FILE, "NFS: direct write(%pD2, %zd@%Ld)\n",
971 		file, iov_iter_count(iter), (long long) iocb->ki_pos);
972 
973 	result = generic_write_checks(iocb, iter);
974 	if (result <= 0)
975 		return result;
976 	count = result;
977 	nfs_add_stats(mapping->host, NFSIOS_DIRECTWRITTENBYTES, count);
978 
979 	pos = iocb->ki_pos;
980 	end = (pos + iov_iter_count(iter) - 1) >> PAGE_SHIFT;
981 
982 	task_io_account_write(count);
983 
984 	result = -ENOMEM;
985 	dreq = nfs_direct_req_alloc();
986 	if (!dreq)
987 		goto out;
988 
989 	dreq->inode = inode;
990 	dreq->bytes_left = dreq->max_count = count;
991 	dreq->io_start = pos;
992 	dreq->ctx = get_nfs_open_context(nfs_file_open_context(iocb->ki_filp));
993 	l_ctx = nfs_get_lock_context(dreq->ctx);
994 	if (IS_ERR(l_ctx)) {
995 		result = PTR_ERR(l_ctx);
996 		nfs_direct_req_release(dreq);
997 		goto out_release;
998 	}
999 	dreq->l_ctx = l_ctx;
1000 	if (!is_sync_kiocb(iocb))
1001 		dreq->iocb = iocb;
1002 
1003 	nfs_start_io_direct(inode);
1004 
1005 	requested = nfs_direct_write_schedule_iovec(dreq, iter, pos);
1006 
1007 	if (mapping->nrpages) {
1008 		invalidate_inode_pages2_range(mapping,
1009 					      pos >> PAGE_SHIFT, end);
1010 	}
1011 
1012 	nfs_end_io_direct(inode);
1013 
1014 	if (requested > 0) {
1015 		result = nfs_direct_wait(dreq);
1016 		if (result > 0) {
1017 			requested -= result;
1018 			iocb->ki_pos = pos + result;
1019 			/* XXX: should check the generic_write_sync retval */
1020 			generic_write_sync(iocb, result);
1021 		}
1022 		iov_iter_revert(iter, requested);
1023 	} else {
1024 		result = requested;
1025 	}
1026 out_release:
1027 	nfs_direct_req_release(dreq);
1028 out:
1029 	return result;
1030 }
1031 
1032 /**
1033  * nfs_init_directcache - create a slab cache for nfs_direct_req structures
1034  *
1035  */
1036 int __init nfs_init_directcache(void)
1037 {
1038 	nfs_direct_cachep = kmem_cache_create("nfs_direct_cache",
1039 						sizeof(struct nfs_direct_req),
1040 						0, (SLAB_RECLAIM_ACCOUNT|
1041 							SLAB_MEM_SPREAD),
1042 						NULL);
1043 	if (nfs_direct_cachep == NULL)
1044 		return -ENOMEM;
1045 
1046 	return 0;
1047 }
1048 
1049 /**
1050  * nfs_destroy_directcache - destroy the slab cache for nfs_direct_req structures
1051  *
1052  */
1053 void nfs_destroy_directcache(void)
1054 {
1055 	kmem_cache_destroy(nfs_direct_cachep);
1056 }
1057