xref: /linux/fs/nfs/write.c (revision abf8efadeb21b741cbd0cc13d57b8f0a207df10d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * linux/fs/nfs/write.c
4  *
5  * Write file data over NFS.
6  *
7  * Copyright (C) 1996, 1997, Olaf Kirch <okir@monad.swb.de>
8  */
9 
10 #include <linux/types.h>
11 #include <linux/slab.h>
12 #include <linux/mm.h>
13 #include <linux/pagemap.h>
14 #include <linux/file.h>
15 #include <linux/writeback.h>
16 #include <linux/swap.h>
17 #include <linux/migrate.h>
18 
19 #include <linux/sunrpc/clnt.h>
20 #include <linux/nfs_fs.h>
21 #include <linux/nfs_mount.h>
22 #include <linux/nfs_page.h>
23 #include <linux/backing-dev.h>
24 #include <linux/export.h>
25 #include <linux/freezer.h>
26 #include <linux/wait.h>
27 #include <linux/iversion.h>
28 #include <linux/filelock.h>
29 
30 #include <linux/uaccess.h>
31 #include <linux/sched/mm.h>
32 
33 #include "delegation.h"
34 #include "internal.h"
35 #include "iostat.h"
36 #include "nfs4_fs.h"
37 #include "fscache.h"
38 #include "pnfs.h"
39 
40 #include "nfstrace.h"
41 
42 #define NFSDBG_FACILITY		NFSDBG_PAGECACHE
43 
44 #define MIN_POOL_WRITE		(32)
45 #define MIN_POOL_COMMIT		(4)
46 
47 struct nfs_io_completion {
48 	void (*complete)(void *data);
49 	void *data;
50 	struct kref refcount;
51 };
52 
53 /*
54  * Local function declarations
55  */
56 static void nfs_redirty_request(struct nfs_page *req);
57 static const struct rpc_call_ops nfs_commit_ops;
58 static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops;
59 static const struct nfs_commit_completion_ops nfs_commit_completion_ops;
60 static const struct nfs_rw_ops nfs_rw_write_ops;
61 static void nfs_inode_remove_request(struct nfs_page *req);
62 static void nfs_clear_request_commit(struct nfs_commit_info *cinfo,
63 				     struct nfs_page *req);
64 static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
65 				      struct inode *inode);
66 
67 static struct kmem_cache *nfs_wdata_cachep;
68 static mempool_t *nfs_wdata_mempool;
69 static struct kmem_cache *nfs_cdata_cachep;
70 static mempool_t *nfs_commit_mempool;
71 
72 struct nfs_commit_data *nfs_commitdata_alloc(void)
73 {
74 	struct nfs_commit_data *p;
75 
76 	p = kmem_cache_zalloc(nfs_cdata_cachep, nfs_io_gfp_mask());
77 	if (!p) {
78 		p = mempool_alloc(nfs_commit_mempool, GFP_NOWAIT);
79 		if (!p)
80 			return NULL;
81 		memset(p, 0, sizeof(*p));
82 	}
83 	INIT_LIST_HEAD(&p->pages);
84 	return p;
85 }
86 EXPORT_SYMBOL_GPL(nfs_commitdata_alloc);
87 
88 void nfs_commit_free(struct nfs_commit_data *p)
89 {
90 	mempool_free(p, nfs_commit_mempool);
91 }
92 EXPORT_SYMBOL_GPL(nfs_commit_free);
93 
94 static struct nfs_pgio_header *nfs_writehdr_alloc(void)
95 {
96 	struct nfs_pgio_header *p;
97 
98 	p = kmem_cache_zalloc(nfs_wdata_cachep, nfs_io_gfp_mask());
99 	if (!p) {
100 		p = mempool_alloc(nfs_wdata_mempool, GFP_NOWAIT);
101 		if (!p)
102 			return NULL;
103 		memset(p, 0, sizeof(*p));
104 	}
105 	p->rw_mode = FMODE_WRITE;
106 	return p;
107 }
108 
109 static void nfs_writehdr_free(struct nfs_pgio_header *hdr)
110 {
111 	mempool_free(hdr, nfs_wdata_mempool);
112 }
113 
114 static struct nfs_io_completion *nfs_io_completion_alloc(gfp_t gfp_flags)
115 {
116 	return kmalloc_obj(struct nfs_io_completion, gfp_flags);
117 }
118 
119 static void nfs_io_completion_init(struct nfs_io_completion *ioc,
120 		void (*complete)(void *), void *data)
121 {
122 	ioc->complete = complete;
123 	ioc->data = data;
124 	kref_init(&ioc->refcount);
125 }
126 
127 static void nfs_io_completion_release(struct kref *kref)
128 {
129 	struct nfs_io_completion *ioc = container_of(kref,
130 			struct nfs_io_completion, refcount);
131 	ioc->complete(ioc->data);
132 	kfree(ioc);
133 }
134 
135 static void nfs_io_completion_get(struct nfs_io_completion *ioc)
136 {
137 	if (ioc != NULL)
138 		kref_get(&ioc->refcount);
139 }
140 
141 static void nfs_io_completion_put(struct nfs_io_completion *ioc)
142 {
143 	if (ioc != NULL)
144 		kref_put(&ioc->refcount, nfs_io_completion_release);
145 }
146 
147 static void
148 nfs_page_set_inode_ref(struct nfs_page *req, struct inode *inode)
149 {
150 	if (!test_and_set_bit(PG_INODE_REF, &req->wb_flags)) {
151 		kref_get(&req->wb_kref);
152 		atomic_long_inc(&NFS_I(inode)->nrequests);
153 	}
154 }
155 
156 static void nfs_cancel_remove_inode(struct nfs_page *req, struct inode *inode)
157 {
158 	if (test_and_clear_bit(PG_REMOVE, &req->wb_flags))
159 		nfs_page_set_inode_ref(req, inode);
160 }
161 
162 /**
163  * nfs_folio_find_head_request - find head request associated with a folio
164  * @folio: pointer to folio
165  *
166  * must be called while holding the inode lock.
167  *
168  * returns matching head request with reference held, or NULL if not found.
169  */
170 static struct nfs_page *nfs_folio_find_head_request(struct folio *folio)
171 {
172 	struct address_space *mapping = folio->mapping;
173 	struct nfs_page *req;
174 
175 	if (!folio_test_private(folio))
176 		return NULL;
177 	spin_lock(&mapping->i_private_lock);
178 	req = folio->private;
179 	if (req) {
180 		WARN_ON_ONCE(req->wb_head != req);
181 		kref_get(&req->wb_kref);
182 	}
183 	spin_unlock(&mapping->i_private_lock);
184 	return req;
185 }
186 
187 /* Adjust the file length if we're writing beyond the end */
188 static void nfs_grow_file(struct folio *folio, unsigned int offset,
189 			  unsigned int count)
190 {
191 	struct inode *inode = folio->mapping->host;
192 	loff_t end, i_size;
193 	pgoff_t end_index;
194 
195 	spin_lock(&inode->i_lock);
196 	i_size = i_size_read(inode);
197 	end_index = ((i_size - 1) >> folio_shift(folio)) << folio_order(folio);
198 	if (i_size > 0 && folio->index < end_index)
199 		goto out;
200 	end = folio_pos(folio) + (loff_t)offset + (loff_t)count;
201 	if (i_size >= end)
202 		goto out;
203 	trace_nfs_size_grow(inode, end);
204 	i_size_write(inode, end);
205 	NFS_I(inode)->cache_validity &= ~NFS_INO_INVALID_SIZE;
206 	nfs_inc_stats(inode, NFSIOS_EXTENDWRITE);
207 out:
208 	/* Atomically update timestamps if they are delegated to us. */
209 	nfs_update_delegated_mtime_locked(inode);
210 	spin_unlock(&inode->i_lock);
211 	nfs_fscache_invalidate(inode, 0);
212 }
213 
214 /* A writeback failed: mark the page as bad, and invalidate the page cache */
215 static void nfs_set_pageerror(struct address_space *mapping)
216 {
217 	struct inode *inode = mapping->host;
218 
219 	nfs_zap_mapping(mapping->host, mapping);
220 	/* Force file size revalidation */
221 	spin_lock(&inode->i_lock);
222 	nfs_set_cache_invalid(inode, NFS_INO_REVAL_FORCED |
223 					     NFS_INO_INVALID_CHANGE |
224 					     NFS_INO_INVALID_SIZE);
225 	spin_unlock(&inode->i_lock);
226 }
227 
228 static void nfs_mapping_set_error(struct folio *folio, int error)
229 {
230 	struct address_space *mapping = folio->mapping;
231 
232 	filemap_set_wb_err(mapping, error);
233 	if (mapping->host)
234 		errseq_set(&mapping->host->i_sb->s_wb_err,
235 			   error == -ENOSPC ? -ENOSPC : -EIO);
236 	nfs_set_pageerror(mapping);
237 }
238 
239 /*
240  * nfs_page_covers_folio
241  * @req: struct nfs_page
242  *
243  * Return true if the request covers the whole folio.
244  * Note that the caller should ensure all subrequests have been joined
245  */
246 static bool nfs_page_group_covers_page(struct nfs_page *req)
247 {
248 	unsigned int len = nfs_folio_length(nfs_page_to_folio(req));
249 
250 	return req->wb_pgbase == 0 && req->wb_bytes == len;
251 }
252 
253 /* We can set the PG_uptodate flag if we see that a write request
254  * covers the full page.
255  */
256 static void nfs_mark_uptodate(struct nfs_page *req)
257 {
258 	struct folio *folio = nfs_page_to_folio(req);
259 
260 	if (folio_test_uptodate(folio))
261 		return;
262 	if (!nfs_page_group_covers_page(req))
263 		return;
264 	folio_mark_uptodate(folio);
265 }
266 
267 static int wb_priority(struct writeback_control *wbc)
268 {
269 	int ret = 0;
270 
271 	if (wbc->sync_mode == WB_SYNC_ALL)
272 		ret = FLUSH_COND_STABLE;
273 	return ret;
274 }
275 
276 /*
277  * NFS congestion control
278  */
279 
280 int nfs_congestion_kb;
281 
282 #define NFS_CONGESTION_ON_THRESH 	(nfs_congestion_kb >> (PAGE_SHIFT-10))
283 #define NFS_CONGESTION_OFF_THRESH	\
284 	(NFS_CONGESTION_ON_THRESH - (NFS_CONGESTION_ON_THRESH >> 2))
285 
286 static void nfs_folio_set_writeback(struct folio *folio)
287 {
288 	struct nfs_server *nfss = NFS_SERVER(folio->mapping->host);
289 
290 	folio_start_writeback(folio);
291 	if (atomic_long_inc_return(&nfss->writeback) > NFS_CONGESTION_ON_THRESH)
292 		nfss->write_congested = 1;
293 }
294 
295 static void nfs_folio_end_writeback(struct folio *folio)
296 {
297 	struct nfs_server *nfss = NFS_SERVER(folio->mapping->host);
298 
299 	folio_end_writeback_no_dropbehind(folio);
300 	if (atomic_long_dec_return(&nfss->writeback) <
301 	    NFS_CONGESTION_OFF_THRESH) {
302 		nfss->write_congested = 0;
303 		wake_up_all(&nfss->write_congestion_wait);
304 	}
305 }
306 
307 static void nfs_page_end_writeback(struct nfs_page *req)
308 {
309 	if (nfs_page_group_sync_on_bit(req, PG_WB_END)) {
310 		nfs_unlock_request(req);
311 		nfs_folio_end_writeback(nfs_page_to_folio(req));
312 	} else
313 		nfs_unlock_request(req);
314 }
315 
316 /*
317  * nfs_destroy_unlinked_subrequests - destroy recently unlinked subrequests
318  *
319  * @destroy_list - request list (using wb_this_page) terminated by @old_head
320  * @old_head - the old head of the list
321  *
322  * All subrequests must be locked and removed from all lists, so at this point
323  * they are only "active" in this function, and possibly in nfs_wait_on_request
324  * with a reference held by some other context.
325  */
326 static void
327 nfs_destroy_unlinked_subrequests(struct nfs_page *destroy_list,
328 				 struct nfs_page *old_head,
329 				 struct inode *inode)
330 {
331 	while (destroy_list) {
332 		struct nfs_page *subreq = destroy_list;
333 
334 		destroy_list = (subreq->wb_this_page == old_head) ?
335 				   NULL : subreq->wb_this_page;
336 
337 		/* Note: lock subreq in order to change subreq->wb_head */
338 		nfs_page_set_headlock(subreq);
339 		WARN_ON_ONCE(old_head != subreq->wb_head);
340 
341 		/* make sure old group is not used */
342 		subreq->wb_this_page = subreq;
343 		subreq->wb_head = subreq;
344 
345 		clear_bit(PG_REMOVE, &subreq->wb_flags);
346 
347 		/* Note: races with nfs_page_group_destroy() */
348 		if (!kref_read(&subreq->wb_kref)) {
349 			/* Check if we raced with nfs_page_group_destroy() */
350 			if (test_and_clear_bit(PG_TEARDOWN, &subreq->wb_flags)) {
351 				nfs_page_clear_headlock(subreq);
352 				nfs_free_request(subreq);
353 			} else
354 				nfs_page_clear_headlock(subreq);
355 			continue;
356 		}
357 		nfs_page_clear_headlock(subreq);
358 
359 		nfs_release_request(old_head);
360 
361 		if (test_and_clear_bit(PG_INODE_REF, &subreq->wb_flags)) {
362 			nfs_release_request(subreq);
363 			atomic_long_dec(&NFS_I(inode)->nrequests);
364 		}
365 
366 		/* subreq is now totally disconnected from page group or any
367 		 * write / commit lists. last chance to wake any waiters */
368 		nfs_unlock_and_release_request(subreq);
369 	}
370 }
371 
372 /*
373  * nfs_join_page_group - destroy subrequests of the head req
374  * @head: the page used to lookup the "page group" of nfs_page structures
375  * @inode: Inode to which the request belongs.
376  *
377  * This function joins all sub requests to the head request by first
378  * locking all requests in the group, cancelling any pending operations
379  * and finally updating the head request to cover the whole range covered by
380  * the (former) group.  All subrequests are removed from any write or commit
381  * lists, unlinked from the group and destroyed.
382  */
383 void nfs_join_page_group(struct nfs_page *head, struct nfs_commit_info *cinfo,
384 			 struct inode *inode)
385 {
386 	struct nfs_page *subreq;
387 	struct nfs_page *destroy_list = NULL;
388 	unsigned int pgbase, off, bytes;
389 
390 	pgbase = head->wb_pgbase;
391 	bytes = head->wb_bytes;
392 	off = head->wb_offset;
393 	for (subreq = head->wb_this_page; subreq != head;
394 			subreq = subreq->wb_this_page) {
395 		/* Subrequests should always form a contiguous range */
396 		if (pgbase > subreq->wb_pgbase) {
397 			off -= pgbase - subreq->wb_pgbase;
398 			bytes += pgbase - subreq->wb_pgbase;
399 			pgbase = subreq->wb_pgbase;
400 		}
401 		bytes = max(subreq->wb_pgbase + subreq->wb_bytes
402 				- pgbase, bytes);
403 	}
404 
405 	/* Set the head request's range to cover the former page group */
406 	head->wb_pgbase = pgbase;
407 	head->wb_bytes = bytes;
408 	head->wb_offset = off;
409 
410 	/* Now that all requests are locked, make sure they aren't on any list.
411 	 * Commit list removal accounting is done after locks are dropped */
412 	subreq = head;
413 	do {
414 		nfs_clear_request_commit(cinfo, subreq);
415 		subreq = subreq->wb_this_page;
416 	} while (subreq != head);
417 
418 	/* unlink subrequests from head, destroy them later */
419 	if (head->wb_this_page != head) {
420 		/* destroy list will be terminated by head */
421 		destroy_list = head->wb_this_page;
422 		head->wb_this_page = head;
423 	}
424 
425 	nfs_destroy_unlinked_subrequests(destroy_list, head, inode);
426 }
427 
428 /**
429  * nfs_wait_on_request - Wait for a request to complete.
430  * @req: request to wait upon.
431  *
432  * Interruptible by fatal signals only.
433  * The user is responsible for holding a count on the request.
434  */
435 static int nfs_wait_on_request(struct nfs_page *req)
436 {
437 	if (!test_bit(PG_BUSY, &req->wb_flags))
438 		return 0;
439 	set_bit(PG_CONTENDED2, &req->wb_flags);
440 	smp_mb__after_atomic();
441 	return wait_on_bit_io(&req->wb_flags, PG_BUSY,
442 			      TASK_UNINTERRUPTIBLE);
443 }
444 
445 /*
446  * nfs_unroll_locks -  unlock all newly locked reqs and wait on @req
447  * @head: head request of page group, must be holding head lock
448  * @req: request that couldn't lock and needs to wait on the req bit lock
449  *
450  * This is a helper function for nfs_lock_and_join_requests
451  * returns 0 on success, < 0 on error.
452  */
453 static void
454 nfs_unroll_locks(struct nfs_page *head, struct nfs_page *req)
455 {
456 	struct nfs_page *tmp;
457 
458 	/* relinquish all the locks successfully grabbed this run */
459 	for (tmp = head->wb_this_page ; tmp != req; tmp = tmp->wb_this_page) {
460 		if (!kref_read(&tmp->wb_kref))
461 			continue;
462 		nfs_unlock_and_release_request(tmp);
463 	}
464 }
465 
466 /*
467  * nfs_page_group_lock_subreq -  try to lock a subrequest
468  * @head: head request of page group
469  * @subreq: request to lock
470  *
471  * This is a helper function for nfs_lock_and_join_requests which
472  * must be called with the head request and page group both locked.
473  * On error, it returns with the page group unlocked.
474  */
475 static int
476 nfs_page_group_lock_subreq(struct nfs_page *head, struct nfs_page *subreq)
477 {
478 	int ret;
479 
480 	if (!kref_get_unless_zero(&subreq->wb_kref))
481 		return 0;
482 	while (!nfs_lock_request(subreq)) {
483 		nfs_page_group_unlock(head);
484 		ret = nfs_wait_on_request(subreq);
485 		if (!ret)
486 			ret = nfs_page_group_lock(head);
487 		if (ret < 0) {
488 			nfs_unroll_locks(head, subreq);
489 			nfs_release_request(subreq);
490 			return ret;
491 		}
492 	}
493 	return 0;
494 }
495 
496 /*
497  * nfs_lock_and_join_requests - join all subreqs to the head req
498  * @folio: the folio used to lookup the "page group" of nfs_page structures
499  *
500  * This function joins all sub requests to the head request by first
501  * locking all requests in the group, cancelling any pending operations
502  * and finally updating the head request to cover the whole range covered by
503  * the (former) group.  All subrequests are removed from any write or commit
504  * lists, unlinked from the group and destroyed.
505  *
506  * Returns a locked, referenced pointer to the head request - which after
507  * this call is guaranteed to be the only request associated with the page.
508  * Returns NULL if no requests are found for @folio, or a ERR_PTR if an
509  * error was encountered.
510  */
511 static struct nfs_page *nfs_lock_and_join_requests(struct folio *folio)
512 {
513 	struct inode *inode = folio->mapping->host;
514 	struct nfs_page *head, *subreq;
515 	struct nfs_commit_info cinfo;
516 	int ret;
517 
518 	/*
519 	 * A reference is taken only on the head request which acts as a
520 	 * reference to the whole page group - the group will not be destroyed
521 	 * until the head reference is released.
522 	 */
523 retry:
524 	head = nfs_folio_find_head_request(folio);
525 	if (!head)
526 		return NULL;
527 
528 	while (!nfs_lock_request(head)) {
529 		ret = nfs_wait_on_request(head);
530 		if (ret < 0) {
531 			nfs_release_request(head);
532 			return ERR_PTR(ret);
533 		}
534 	}
535 
536 	ret = nfs_page_group_lock(head);
537 	if (ret < 0)
538 		goto out_unlock;
539 
540 	/* Ensure that nobody removed the request before we locked it */
541 	if (head != folio->private) {
542 		nfs_page_group_unlock(head);
543 		nfs_unlock_and_release_request(head);
544 		goto retry;
545 	}
546 
547 	nfs_cancel_remove_inode(head, inode);
548 
549 	/* lock each request in the page group */
550 	for (subreq = head->wb_this_page;
551 	     subreq != head;
552 	     subreq = subreq->wb_this_page) {
553 		ret = nfs_page_group_lock_subreq(head, subreq);
554 		if (ret < 0)
555 			goto out_unlock;
556 	}
557 
558 	nfs_page_group_unlock(head);
559 
560 	nfs_init_cinfo_from_inode(&cinfo, inode);
561 	nfs_join_page_group(head, &cinfo, inode);
562 	return head;
563 
564 out_unlock:
565 	nfs_unlock_and_release_request(head);
566 	return ERR_PTR(ret);
567 }
568 
569 static void nfs_write_error(struct nfs_page *req, int error)
570 {
571 	trace_nfs_write_error(nfs_page_to_inode(req), req, error);
572 	nfs_mapping_set_error(nfs_page_to_folio(req), error);
573 	nfs_inode_remove_request(req);
574 	nfs_page_end_writeback(req);
575 	nfs_release_request(req);
576 }
577 
578 /*
579  * Find an associated nfs write request, and prepare to flush it out
580  * May return an error if the user signalled nfs_wait_on_request().
581  */
582 static int nfs_do_writepage(struct folio *folio, struct writeback_control *wbc,
583 		struct nfs_pageio_descriptor *pgio)
584 {
585 	struct nfs_page *req;
586 	int ret;
587 
588 	nfs_pageio_cond_complete(pgio, folio->index);
589 
590 	req = nfs_lock_and_join_requests(folio);
591 	if (!req)
592 		return 0;
593 	if (IS_ERR(req))
594 		return PTR_ERR(req);
595 
596 	trace_nfs_do_writepage(req);
597 	nfs_folio_set_writeback(folio);
598 	WARN_ON_ONCE(test_bit(PG_CLEAN, &req->wb_flags));
599 
600 	/* If there is a fatal error that covers this write, just exit */
601 	ret = pgio->pg_error;
602 	if (nfs_error_is_fatal_on_server(ret))
603 		goto out_launder;
604 
605 	if (!nfs_pageio_add_request(pgio, req)) {
606 		ret = pgio->pg_error;
607 		/*
608 		 * Remove the problematic req upon fatal errors on the server
609 		 */
610 		if (nfs_error_is_fatal_on_server(ret))
611 			goto out_launder;
612 		folio_redirty_for_writepage(wbc, folio);
613 		nfs_redirty_request(req);
614 		pgio->pg_error = 0;
615 		return ret;
616 	}
617 
618 	nfs_add_stats(folio->mapping->host, NFSIOS_WRITEPAGES, 1);
619 	return 0;
620 
621 out_launder:
622 	nfs_write_error(req, ret);
623 	return 0;
624 }
625 
626 /*
627  * Write an mmapped page to the server.
628  */
629 static int nfs_writepage_locked(struct folio *folio,
630 				struct writeback_control *wbc)
631 {
632 	struct nfs_pageio_descriptor pgio;
633 	struct inode *inode = folio->mapping->host;
634 	int err;
635 
636 	nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGE);
637 	nfs_pageio_init_write(&pgio, inode, 0, false,
638 			      &nfs_async_write_completion_ops);
639 	err = nfs_do_writepage(folio, wbc, &pgio);
640 	pgio.pg_error = 0;
641 	nfs_pageio_complete(&pgio);
642 	return err;
643 }
644 
645 static void nfs_io_completion_commit(void *inode)
646 {
647 	nfs_commit_inode(inode, 0);
648 }
649 
650 int nfs_writepages(struct address_space *mapping, struct writeback_control *wbc)
651 {
652 	struct inode *inode = mapping->host;
653 	struct nfs_pageio_descriptor pgio;
654 	struct nfs_io_completion *ioc = NULL;
655 	unsigned int mntflags = NFS_SERVER(inode)->flags;
656 	struct nfs_server *nfss = NFS_SERVER(inode);
657 	int priority = 0;
658 	int err;
659 
660 	trace_nfs_writepages(inode, wbc->range_start, wbc->range_end - wbc->range_start);
661 
662 	/* Wait with writeback until write congestion eases */
663 	if (wbc->sync_mode == WB_SYNC_NONE && nfss->write_congested) {
664 		err = wait_event_killable(nfss->write_congestion_wait,
665 					  nfss->write_congested == 0);
666 		if (err)
667 			goto out_err;
668 	}
669 
670 	nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGES);
671 
672 	if (!(mntflags & NFS_MOUNT_WRITE_EAGER) || wbc->for_kupdate ||
673 	    wbc->for_background || wbc->for_sync) {
674 		ioc = nfs_io_completion_alloc(GFP_KERNEL);
675 		if (ioc)
676 			nfs_io_completion_init(ioc, nfs_io_completion_commit,
677 					       inode);
678 		priority = wb_priority(wbc);
679 	}
680 
681 	do {
682 		struct folio *folio = NULL;
683 
684 		nfs_pageio_init_write(&pgio, inode, priority, false,
685 				      &nfs_async_write_completion_ops);
686 		pgio.pg_io_completion = ioc;
687 		while ((folio = writeback_iter(mapping, wbc, folio, &err))) {
688 			err = nfs_do_writepage(folio, wbc, &pgio);
689 			folio_unlock(folio);
690 		}
691 		pgio.pg_error = 0;
692 		nfs_pageio_complete(&pgio);
693 		if (err == -EAGAIN && mntflags & NFS_MOUNT_SOFTERR)
694 			break;
695 	} while (err < 0 && !nfs_error_is_fatal(err));
696 	nfs_io_completion_put(ioc);
697 
698 	if (err > 0)
699 		err = 0;
700 out_err:
701 	trace_nfs_writepages_done(inode, wbc->range_start, wbc->range_end - wbc->range_start, err);
702 	return err;
703 }
704 
705 /*
706  * Insert a write request into an inode
707  */
708 static void nfs_inode_add_request(struct nfs_page *req)
709 {
710 	struct folio *folio = nfs_page_to_folio(req);
711 	struct address_space *mapping = folio->mapping;
712 	struct nfs_inode *nfsi = NFS_I(mapping->host);
713 
714 	WARN_ON_ONCE(req->wb_this_page != req);
715 
716 	/* Lock the request! */
717 	nfs_lock_request(req);
718 	spin_lock(&mapping->i_private_lock);
719 	set_bit(PG_MAPPED, &req->wb_flags);
720 	folio->private = req;
721 	spin_unlock(&mapping->i_private_lock);
722 	atomic_long_inc(&nfsi->nrequests);
723 	/* this a head request for a page group - mark it as having an
724 	 * extra reference so sub groups can follow suit.
725 	 * This flag also informs pgio layer when to bump nrequests when
726 	 * adding subrequests. */
727 	WARN_ON(test_and_set_bit(PG_INODE_REF, &req->wb_flags));
728 	kref_get(&req->wb_kref);
729 }
730 
731 /*
732  * Remove a write request from an inode
733  */
734 static void nfs_inode_remove_request(struct nfs_page *req)
735 {
736 	struct nfs_inode *nfsi = NFS_I(nfs_page_to_inode(req));
737 
738 	nfs_page_group_lock(req);
739 	if (nfs_page_group_sync_on_bit_locked(req, PG_REMOVE)) {
740 		struct folio *folio = nfs_page_to_folio(req->wb_head);
741 
742 		if (likely(folio)) {
743 			struct address_space *mapping = folio->mapping;
744 
745 			spin_lock(&mapping->i_private_lock);
746 			folio->private = NULL;
747 			clear_bit(PG_MAPPED, &req->wb_head->wb_flags);
748 			spin_unlock(&mapping->i_private_lock);
749 
750 			folio_end_dropbehind(folio);
751 		}
752 	}
753 	nfs_page_group_unlock(req);
754 
755 	if (test_and_clear_bit(PG_INODE_REF, &req->wb_flags)) {
756 		atomic_long_dec(&nfsi->nrequests);
757 		nfs_release_request(req);
758 	}
759 }
760 
761 static void nfs_mark_request_dirty(struct nfs_page *req)
762 {
763 	struct folio *folio = nfs_page_to_folio(req);
764 	if (folio)
765 		filemap_dirty_folio(folio_mapping(folio), folio);
766 }
767 
768 /**
769  * nfs_request_add_commit_list_locked - add request to a commit list
770  * @req: pointer to a struct nfs_page
771  * @dst: commit list head
772  * @cinfo: holds list lock and accounting info
773  *
774  * This sets the PG_CLEAN bit, updates the cinfo count of
775  * number of outstanding requests requiring a commit as well as
776  * the MM page stats.
777  *
778  * The caller must hold NFS_I(cinfo->inode)->commit_mutex, and the
779  * nfs_page lock.
780  */
781 void
782 nfs_request_add_commit_list_locked(struct nfs_page *req, struct list_head *dst,
783 			    struct nfs_commit_info *cinfo)
784 {
785 	set_bit(PG_CLEAN, &req->wb_flags);
786 	nfs_list_add_request(req, dst);
787 	atomic_long_inc(&cinfo->mds->ncommit);
788 }
789 EXPORT_SYMBOL_GPL(nfs_request_add_commit_list_locked);
790 
791 /**
792  * nfs_request_add_commit_list - add request to a commit list
793  * @req: pointer to a struct nfs_page
794  * @cinfo: holds list lock and accounting info
795  *
796  * This sets the PG_CLEAN bit, updates the cinfo count of
797  * number of outstanding requests requiring a commit as well as
798  * the MM page stats.
799  *
800  * The caller must _not_ hold the cinfo->lock, but must be
801  * holding the nfs_page lock.
802  */
803 void
804 nfs_request_add_commit_list(struct nfs_page *req, struct nfs_commit_info *cinfo)
805 {
806 	mutex_lock(&NFS_I(cinfo->inode)->commit_mutex);
807 	nfs_request_add_commit_list_locked(req, &cinfo->mds->list, cinfo);
808 	mutex_unlock(&NFS_I(cinfo->inode)->commit_mutex);
809 	nfs_folio_mark_unstable(req, cinfo);
810 }
811 EXPORT_SYMBOL_GPL(nfs_request_add_commit_list);
812 
813 /**
814  * nfs_request_remove_commit_list - Remove request from a commit list
815  * @req: pointer to a nfs_page
816  * @cinfo: holds list lock and accounting info
817  *
818  * This clears the PG_CLEAN bit, and updates the cinfo's count of
819  * number of outstanding requests requiring a commit
820  * It does not update the MM page stats.
821  *
822  * The caller _must_ hold the cinfo->lock and the nfs_page lock.
823  */
824 void
825 nfs_request_remove_commit_list(struct nfs_page *req,
826 			       struct nfs_commit_info *cinfo)
827 {
828 	if (!test_and_clear_bit(PG_CLEAN, &(req)->wb_flags))
829 		return;
830 	nfs_list_remove_request(req);
831 	atomic_long_dec(&cinfo->mds->ncommit);
832 }
833 EXPORT_SYMBOL_GPL(nfs_request_remove_commit_list);
834 
835 static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
836 				      struct inode *inode)
837 {
838 	cinfo->inode = inode;
839 	cinfo->mds = &NFS_I(inode)->commit_info;
840 	cinfo->ds = pnfs_get_ds_info(inode);
841 	cinfo->dreq = NULL;
842 	cinfo->completion_ops = &nfs_commit_completion_ops;
843 }
844 
845 void nfs_init_cinfo(struct nfs_commit_info *cinfo,
846 		    struct inode *inode,
847 		    struct nfs_direct_req *dreq)
848 {
849 	if (dreq)
850 		nfs_init_cinfo_from_dreq(cinfo, dreq);
851 	else
852 		nfs_init_cinfo_from_inode(cinfo, inode);
853 }
854 EXPORT_SYMBOL_GPL(nfs_init_cinfo);
855 
856 /*
857  * Add a request to the inode's commit list.
858  */
859 void
860 nfs_mark_request_commit(struct nfs_page *req, struct pnfs_layout_segment *lseg,
861 			struct nfs_commit_info *cinfo, u32 ds_commit_idx)
862 {
863 	if (pnfs_mark_request_commit(req, lseg, cinfo, ds_commit_idx))
864 		return;
865 	nfs_request_add_commit_list(req, cinfo);
866 }
867 
868 static void nfs_folio_clear_commit(struct nfs_page *req)
869 {
870 	struct folio *folio = nfs_page_to_folio(req);
871 
872 	if (folio) {
873 		long nr = DIV_ROUND_UP(req->wb_bytes, PAGE_SIZE);
874 
875 		node_stat_mod_folio(folio, NR_WRITEBACK, -nr);
876 		bdi_wb_stat_mod(folio->mapping->host, WB_WRITEBACK, -nr);
877 	}
878 }
879 
880 /* Called holding the request lock on @req */
881 static void nfs_clear_request_commit(struct nfs_commit_info *cinfo,
882 				     struct nfs_page *req)
883 {
884 	if (test_bit(PG_CLEAN, &req->wb_flags)) {
885 		struct nfs_open_context *ctx = nfs_req_openctx(req);
886 		struct inode *inode = d_inode(ctx->dentry);
887 
888 		mutex_lock(&NFS_I(inode)->commit_mutex);
889 		if (!pnfs_clear_request_commit(req, cinfo)) {
890 			nfs_request_remove_commit_list(req, cinfo);
891 		}
892 		mutex_unlock(&NFS_I(inode)->commit_mutex);
893 		nfs_folio_clear_commit(req);
894 	}
895 }
896 
897 int nfs_write_need_commit(struct nfs_pgio_header *hdr)
898 {
899 	if (hdr->verf.committed == NFS_DATA_SYNC)
900 		return hdr->lseg == NULL;
901 	return hdr->verf.committed != NFS_FILE_SYNC;
902 }
903 
904 static void nfs_async_write_init(struct nfs_pgio_header *hdr)
905 {
906 	nfs_io_completion_get(hdr->io_completion);
907 }
908 
909 static void nfs_write_completion(struct nfs_pgio_header *hdr)
910 {
911 	struct nfs_commit_info cinfo;
912 	unsigned long bytes = 0;
913 
914 	if (test_bit(NFS_IOHDR_REDO, &hdr->flags))
915 		goto out;
916 	nfs_init_cinfo_from_inode(&cinfo, hdr->inode);
917 	while (!list_empty(&hdr->pages)) {
918 		struct nfs_page *req = nfs_list_entry(hdr->pages.next);
919 
920 		bytes += req->wb_bytes;
921 		nfs_list_remove_request(req);
922 		if (test_bit(NFS_IOHDR_ERROR, &hdr->flags) &&
923 		    (hdr->good_bytes < bytes)) {
924 			trace_nfs_comp_error(hdr->inode, req, hdr->error);
925 			nfs_mapping_set_error(nfs_page_to_folio(req),
926 					      hdr->error);
927 			goto remove_req;
928 		}
929 		if (nfs_write_need_commit(hdr)) {
930 			struct nfs_open_context *ctx =
931 				req->wb_lock_context->open_context;
932 
933 			/* Reset wb_nio, since the write was successful. */
934 			req->wb_nio = 0;
935 			memcpy(&req->wb_verf, &hdr->verf.verifier, sizeof(req->wb_verf));
936 			clear_bit(NFS_CONTEXT_WRITE_SYNC, &ctx->flags);
937 			nfs_mark_request_commit(req, hdr->lseg, &cinfo,
938 				hdr->ds_commit_idx);
939 			goto next;
940 		}
941 remove_req:
942 		nfs_inode_remove_request(req);
943 next:
944 		nfs_page_end_writeback(req);
945 		nfs_release_request(req);
946 	}
947 out:
948 	nfs_io_completion_put(hdr->io_completion);
949 	hdr->release(hdr);
950 }
951 
952 unsigned long
953 nfs_reqs_to_commit(struct nfs_commit_info *cinfo)
954 {
955 	return atomic_long_read(&cinfo->mds->ncommit);
956 }
957 
958 /* NFS_I(cinfo->inode)->commit_mutex held by caller */
959 int
960 nfs_scan_commit_list(struct list_head *src, struct list_head *dst,
961 		     struct nfs_commit_info *cinfo, int max)
962 {
963 	struct nfs_page *req, *tmp;
964 	int ret = 0;
965 
966 	list_for_each_entry_safe(req, tmp, src, wb_list) {
967 		kref_get(&req->wb_kref);
968 		if (!nfs_lock_request(req)) {
969 			nfs_release_request(req);
970 			continue;
971 		}
972 		nfs_request_remove_commit_list(req, cinfo);
973 		clear_bit(PG_COMMIT_TO_DS, &req->wb_flags);
974 		nfs_list_add_request(req, dst);
975 		ret++;
976 		if ((ret == max) && !cinfo->dreq)
977 			break;
978 		cond_resched();
979 	}
980 	return ret;
981 }
982 EXPORT_SYMBOL_GPL(nfs_scan_commit_list);
983 
984 /*
985  * nfs_scan_commit - Scan an inode for commit requests
986  * @inode: NFS inode to scan
987  * @dst: mds destination list
988  * @cinfo: mds and ds lists of reqs ready to commit
989  *
990  * Moves requests from the inode's 'commit' request list.
991  * The requests are *not* checked to ensure that they form a contiguous set.
992  */
993 int
994 nfs_scan_commit(struct inode *inode, struct list_head *dst,
995 		struct nfs_commit_info *cinfo)
996 {
997 	int ret = 0;
998 
999 	if (!atomic_long_read(&cinfo->mds->ncommit))
1000 		return 0;
1001 	mutex_lock(&NFS_I(cinfo->inode)->commit_mutex);
1002 	if (atomic_long_read(&cinfo->mds->ncommit) > 0) {
1003 		const int max = INT_MAX;
1004 
1005 		ret = nfs_scan_commit_list(&cinfo->mds->list, dst,
1006 					   cinfo, max);
1007 		ret += pnfs_scan_commit_lists(inode, cinfo, max - ret);
1008 	}
1009 	mutex_unlock(&NFS_I(cinfo->inode)->commit_mutex);
1010 	return ret;
1011 }
1012 
1013 /*
1014  * Search for an existing write request, and attempt to update
1015  * it to reflect a new dirty region on a given page.
1016  *
1017  * If the attempt fails, then the existing request is flushed out
1018  * to disk.
1019  */
1020 static struct nfs_page *nfs_try_to_update_request(struct folio *folio,
1021 						  unsigned int offset,
1022 						  unsigned int bytes)
1023 {
1024 	struct nfs_page *req;
1025 	unsigned int rqend;
1026 	unsigned int end;
1027 	int error;
1028 
1029 	trace_nfs_try_to_update_request(folio_inode(folio), offset, bytes);
1030 	end = offset + bytes;
1031 
1032 	req = nfs_lock_and_join_requests(folio);
1033 	if (IS_ERR_OR_NULL(req))
1034 		goto out;
1035 
1036 	rqend = req->wb_offset + req->wb_bytes;
1037 	/*
1038 	 * Tell the caller to flush out the request if
1039 	 * the offsets are non-contiguous.
1040 	 * Note: nfs_flush_incompatible() will already
1041 	 * have flushed out requests having wrong owners.
1042 	 */
1043 	if (offset > rqend || end < req->wb_offset)
1044 		goto out_flushme;
1045 
1046 	/* Okay, the request matches. Update the region */
1047 	if (offset < req->wb_offset) {
1048 		req->wb_offset = offset;
1049 		req->wb_pgbase = offset;
1050 	}
1051 	if (end > rqend)
1052 		req->wb_bytes = end - req->wb_offset;
1053 	else
1054 		req->wb_bytes = rqend - req->wb_offset;
1055 	req->wb_nio = 0;
1056 out:
1057 	trace_nfs_try_to_update_request_done(folio_inode(folio), offset, bytes,
1058 					     PTR_ERR_OR_ZERO(req));
1059 	return req;
1060 out_flushme:
1061 	/*
1062 	 * Note: we mark the request dirty here because
1063 	 * nfs_lock_and_join_requests() cannot preserve
1064 	 * commit flags, so we have to replay the write.
1065 	 */
1066 	nfs_mark_request_dirty(req);
1067 	nfs_unlock_and_release_request(req);
1068 	error = nfs_wb_folio(folio->mapping->host, folio);
1069 	trace_nfs_try_to_update_request_done(folio_inode(folio), offset, bytes, error);
1070 	return (error < 0) ? ERR_PTR(error) : NULL;
1071 }
1072 
1073 /*
1074  * Try to update an existing write request, or create one if there is none.
1075  *
1076  * Note: Should always be called with the Page Lock held to prevent races
1077  * if we have to add a new request. Also assumes that the caller has
1078  * already called nfs_flush_incompatible() if necessary.
1079  */
1080 static struct nfs_page *nfs_setup_write_request(struct nfs_open_context *ctx,
1081 						struct folio *folio,
1082 						unsigned int offset,
1083 						unsigned int bytes)
1084 {
1085 	struct nfs_page *req;
1086 
1087 	req = nfs_try_to_update_request(folio, offset, bytes);
1088 	if (req != NULL)
1089 		goto out;
1090 	req = nfs_page_create_from_folio(ctx, folio, offset, bytes);
1091 	if (IS_ERR(req))
1092 		goto out;
1093 	nfs_inode_add_request(req);
1094 out:
1095 	return req;
1096 }
1097 
1098 static int nfs_writepage_setup(struct nfs_open_context *ctx,
1099 			       struct folio *folio, unsigned int offset,
1100 			       unsigned int count)
1101 {
1102 	struct nfs_page *req;
1103 
1104 	req = nfs_setup_write_request(ctx, folio, offset, count);
1105 	if (IS_ERR(req))
1106 		return PTR_ERR(req);
1107 	trace_nfs_writepage_setup(req);
1108 	/* Update file length */
1109 	nfs_grow_file(folio, offset, count);
1110 	nfs_mark_uptodate(req);
1111 	nfs_mark_request_dirty(req);
1112 	nfs_unlock_and_release_request(req);
1113 	return 0;
1114 }
1115 
1116 int nfs_flush_incompatible(struct file *file, struct folio *folio)
1117 {
1118 	struct nfs_open_context *ctx = nfs_file_open_context(file);
1119 	struct nfs_lock_context *l_ctx;
1120 	struct file_lock_context *flctx = locks_inode_context(file_inode(file));
1121 	struct nfs_page	*req;
1122 	int do_flush, status;
1123 	/*
1124 	 * Look for a request corresponding to this page. If there
1125 	 * is one, and it belongs to another file, we flush it out
1126 	 * before we try to copy anything into the page. Do this
1127 	 * due to the lack of an ACCESS-type call in NFSv2.
1128 	 * Also do the same if we find a request from an existing
1129 	 * dropped page.
1130 	 */
1131 	do {
1132 		req = nfs_folio_find_head_request(folio);
1133 		if (req == NULL)
1134 			return 0;
1135 		l_ctx = req->wb_lock_context;
1136 		do_flush = nfs_page_to_folio(req) != folio ||
1137 			   !nfs_match_open_context(nfs_req_openctx(req), ctx);
1138 		if (l_ctx && flctx &&
1139 		    !(list_empty_careful(&flctx->flc_posix) &&
1140 		      list_empty_careful(&flctx->flc_flock))) {
1141 			do_flush |= l_ctx->lockowner != current->files;
1142 		}
1143 		nfs_release_request(req);
1144 		if (!do_flush)
1145 			return 0;
1146 		status = nfs_wb_folio(folio->mapping->host, folio);
1147 	} while (status == 0);
1148 	return status;
1149 }
1150 
1151 /*
1152  * Avoid buffered writes when a open context credential's key would
1153  * expire soon.
1154  *
1155  * Returns -EACCES if the key will expire within RPC_KEY_EXPIRE_FAIL.
1156  *
1157  * Return 0 and set a credential flag which triggers the inode to flush
1158  * and performs  NFS_FILE_SYNC writes if the key will expired within
1159  * RPC_KEY_EXPIRE_TIMEO.
1160  */
1161 int
1162 nfs_key_timeout_notify(struct file *filp, struct inode *inode)
1163 {
1164 	struct nfs_open_context *ctx = nfs_file_open_context(filp);
1165 
1166 	if (nfs_ctx_key_to_expire(ctx, inode) &&
1167 	    !rcu_access_pointer(ctx->ll_cred))
1168 		/* Already expired! */
1169 		return -EACCES;
1170 	return 0;
1171 }
1172 
1173 /*
1174  * Test if the open context credential key is marked to expire soon.
1175  */
1176 bool nfs_ctx_key_to_expire(struct nfs_open_context *ctx, struct inode *inode)
1177 {
1178 	struct rpc_auth *auth = NFS_SERVER(inode)->client->cl_auth;
1179 	struct rpc_cred *cred, *new, *old = NULL;
1180 	struct auth_cred acred = {
1181 		.cred = ctx->cred,
1182 	};
1183 	bool ret = false;
1184 
1185 	rcu_read_lock();
1186 	cred = rcu_dereference(ctx->ll_cred);
1187 	if (cred && !(cred->cr_ops->crkey_timeout &&
1188 		      cred->cr_ops->crkey_timeout(cred)))
1189 		goto out;
1190 	rcu_read_unlock();
1191 
1192 	new = auth->au_ops->lookup_cred(auth, &acred, 0);
1193 	if (new == cred) {
1194 		put_rpccred(new);
1195 		return true;
1196 	}
1197 	if (IS_ERR_OR_NULL(new)) {
1198 		new = NULL;
1199 		ret = true;
1200 	} else if (new->cr_ops->crkey_timeout &&
1201 		   new->cr_ops->crkey_timeout(new))
1202 		ret = true;
1203 
1204 	rcu_read_lock();
1205 	old = rcu_dereference_protected(xchg(&ctx->ll_cred,
1206 					     RCU_INITIALIZER(new)), 1);
1207 out:
1208 	rcu_read_unlock();
1209 	put_rpccred(old);
1210 	return ret;
1211 }
1212 
1213 /*
1214  * If the page cache is marked as unsafe or invalid, then we can't rely on
1215  * the PageUptodate() flag. In this case, we will need to turn off
1216  * write optimisations that depend on the page contents being correct.
1217  */
1218 static bool nfs_folio_write_uptodate(struct folio *folio, unsigned int pagelen)
1219 {
1220 	struct inode *inode = folio->mapping->host;
1221 	struct nfs_inode *nfsi = NFS_I(inode);
1222 
1223 	if (nfs_have_delegated_attributes(inode))
1224 		goto out;
1225 	if (nfsi->cache_validity &
1226 	    (NFS_INO_INVALID_CHANGE | NFS_INO_INVALID_SIZE))
1227 		return false;
1228 	smp_rmb();
1229 	if (test_bit(NFS_INO_INVALIDATING, &nfsi->flags) && pagelen != 0)
1230 		return false;
1231 out:
1232 	if (nfsi->cache_validity & NFS_INO_INVALID_DATA && pagelen != 0)
1233 		return false;
1234 	return folio_test_uptodate(folio) != 0;
1235 }
1236 
1237 static bool
1238 is_whole_file_wrlock(struct file_lock *fl)
1239 {
1240 	return fl->fl_start == 0 && fl->fl_end == OFFSET_MAX &&
1241 			lock_is_write(fl);
1242 }
1243 
1244 /* If we know the page is up to date, and we're not using byte range locks (or
1245  * if we have the whole file locked for writing), it may be more efficient to
1246  * extend the write to cover the entire page in order to avoid fragmentation
1247  * inefficiencies.
1248  *
1249  * If the file is opened for synchronous writes then we can just skip the rest
1250  * of the checks.
1251  */
1252 static int nfs_can_extend_write(struct file *file, struct folio *folio,
1253 				unsigned int pagelen)
1254 {
1255 	struct inode *inode = file_inode(file);
1256 	struct file_lock_context *flctx = locks_inode_context(inode);
1257 	struct file_lock *fl;
1258 	int ret;
1259 	unsigned int mntflags = NFS_SERVER(inode)->flags;
1260 
1261 	if (mntflags & NFS_MOUNT_NO_ALIGNWRITE)
1262 		return 0;
1263 	if (file->f_flags & O_DSYNC)
1264 		return 0;
1265 	if (!nfs_folio_write_uptodate(folio, pagelen))
1266 		return 0;
1267 	if (nfs_have_write_delegation(inode))
1268 		return 1;
1269 	if (!flctx || (list_empty_careful(&flctx->flc_flock) &&
1270 		       list_empty_careful(&flctx->flc_posix)))
1271 		return 1;
1272 
1273 	/* Check to see if there are whole file write locks */
1274 	ret = 0;
1275 	spin_lock(&flctx->flc_lock);
1276 	if (!list_empty(&flctx->flc_posix)) {
1277 		fl = list_first_entry(&flctx->flc_posix, struct file_lock,
1278 					c.flc_list);
1279 		if (is_whole_file_wrlock(fl))
1280 			ret = 1;
1281 	} else if (!list_empty(&flctx->flc_flock)) {
1282 		fl = list_first_entry(&flctx->flc_flock, struct file_lock,
1283 					c.flc_list);
1284 		if (lock_is_write(fl))
1285 			ret = 1;
1286 	}
1287 	spin_unlock(&flctx->flc_lock);
1288 	return ret;
1289 }
1290 
1291 /*
1292  * Update and possibly write a cached page of an NFS file.
1293  *
1294  * XXX: Keep an eye on generic_file_read to make sure it doesn't do bad
1295  * things with a page scheduled for an RPC call (e.g. invalidate it).
1296  */
1297 int nfs_update_folio(struct file *file, struct folio *folio,
1298 		     unsigned int offset, unsigned int count)
1299 {
1300 	struct nfs_open_context *ctx = nfs_file_open_context(file);
1301 	struct address_space *mapping = folio->mapping;
1302 	struct inode *inode = mapping->host;
1303 	unsigned int pagelen = nfs_folio_length(folio);
1304 	int		status = 0;
1305 
1306 	nfs_inc_stats(inode, NFSIOS_VFSUPDATEPAGE);
1307 
1308 	trace_nfs_update_folio(inode, offset, count);
1309 
1310 	dprintk("NFS:       nfs_update_folio(%pD2 %d@%lld)\n", file, count,
1311 		(long long)(folio_pos(folio) + offset));
1312 
1313 	if (!count)
1314 		goto out;
1315 
1316 	if (nfs_can_extend_write(file, folio, pagelen)) {
1317 		unsigned int end = count + offset;
1318 
1319 		offset = round_down(offset, PAGE_SIZE);
1320 		if (end < pagelen)
1321 			end = min(round_up(end, PAGE_SIZE), pagelen);
1322 		count = end - offset;
1323 	}
1324 
1325 	status = nfs_writepage_setup(ctx, folio, offset, count);
1326 	if (status < 0)
1327 		nfs_set_pageerror(mapping);
1328 out:
1329 	trace_nfs_update_folio_done(inode, offset, count, status);
1330 	dprintk("NFS:       nfs_update_folio returns %d (isize %lld)\n",
1331 			status, (long long)i_size_read(inode));
1332 	return status;
1333 }
1334 
1335 static int flush_task_priority(int how)
1336 {
1337 	switch (how & (FLUSH_HIGHPRI|FLUSH_LOWPRI)) {
1338 		case FLUSH_HIGHPRI:
1339 			return RPC_PRIORITY_HIGH;
1340 		case FLUSH_LOWPRI:
1341 			return RPC_PRIORITY_LOW;
1342 	}
1343 	return RPC_PRIORITY_NORMAL;
1344 }
1345 
1346 static void nfs_initiate_write(struct nfs_pgio_header *hdr,
1347 			       struct rpc_message *msg,
1348 			       const struct nfs_rpc_ops *rpc_ops,
1349 			       struct rpc_task_setup *task_setup_data, int how)
1350 {
1351 	int priority = flush_task_priority(how);
1352 
1353 	if (IS_SWAPFILE(hdr->inode))
1354 		task_setup_data->flags |= RPC_TASK_SWAPPER;
1355 	task_setup_data->priority = priority;
1356 	rpc_ops->write_setup(hdr, msg, &task_setup_data->rpc_client);
1357 	trace_nfs_initiate_write(hdr);
1358 }
1359 
1360 /* If a nfs_flush_* function fails, it should remove reqs from @head and
1361  * call this on each, which will prepare them to be retried on next
1362  * writeback using standard nfs.
1363  */
1364 static void nfs_redirty_request(struct nfs_page *req)
1365 {
1366 	struct nfs_inode *nfsi = NFS_I(nfs_page_to_inode(req));
1367 
1368 	/* Bump the transmission count */
1369 	req->wb_nio++;
1370 	nfs_mark_request_dirty(req);
1371 	atomic_long_inc(&nfsi->redirtied_pages);
1372 	nfs_page_end_writeback(req);
1373 	nfs_release_request(req);
1374 }
1375 
1376 static void nfs_async_write_error(struct list_head *head, int error)
1377 {
1378 	struct nfs_page	*req;
1379 
1380 	while (!list_empty(head)) {
1381 		req = nfs_list_entry(head->next);
1382 		nfs_list_remove_request(req);
1383 		if (nfs_error_is_fatal_on_server(error))
1384 			nfs_write_error(req, error);
1385 		else
1386 			nfs_redirty_request(req);
1387 	}
1388 }
1389 
1390 static void nfs_async_write_reschedule_io(struct nfs_pgio_header *hdr)
1391 {
1392 	nfs_async_write_error(&hdr->pages, 0);
1393 }
1394 
1395 static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops = {
1396 	.init_hdr = nfs_async_write_init,
1397 	.error_cleanup = nfs_async_write_error,
1398 	.completion = nfs_write_completion,
1399 	.reschedule_io = nfs_async_write_reschedule_io,
1400 };
1401 
1402 void nfs_pageio_init_write(struct nfs_pageio_descriptor *pgio,
1403 			       struct inode *inode, int ioflags, bool force_mds,
1404 			       const struct nfs_pgio_completion_ops *compl_ops)
1405 {
1406 	struct nfs_server *server = NFS_SERVER(inode);
1407 	const struct nfs_pageio_ops *pg_ops = &nfs_pgio_rw_ops;
1408 
1409 #if IS_ENABLED(CONFIG_NFS_V4)
1410 	if (server->pnfs_curr_ld && !force_mds)
1411 		pg_ops = server->pnfs_curr_ld->pg_write_ops;
1412 #endif
1413 	nfs_pageio_init(pgio, inode, pg_ops, compl_ops, &nfs_rw_write_ops,
1414 			server->wsize, ioflags);
1415 }
1416 EXPORT_SYMBOL_GPL(nfs_pageio_init_write);
1417 
1418 void nfs_pageio_reset_write_mds(struct nfs_pageio_descriptor *pgio)
1419 {
1420 	struct nfs_pgio_mirror *mirror;
1421 
1422 	if (pgio->pg_ops && pgio->pg_ops->pg_cleanup)
1423 		pgio->pg_ops->pg_cleanup(pgio);
1424 
1425 	pgio->pg_ops = &nfs_pgio_rw_ops;
1426 
1427 	nfs_pageio_stop_mirroring(pgio);
1428 
1429 	mirror = &pgio->pg_mirrors[0];
1430 	mirror->pg_bsize = NFS_SERVER(pgio->pg_inode)->wsize;
1431 }
1432 EXPORT_SYMBOL_GPL(nfs_pageio_reset_write_mds);
1433 
1434 
1435 void nfs_commit_prepare(struct rpc_task *task, void *calldata)
1436 {
1437 	struct nfs_commit_data *data = calldata;
1438 
1439 	NFS_PROTO(data->inode)->commit_rpc_prepare(task, data);
1440 }
1441 
1442 static void nfs_writeback_check_extend(struct nfs_pgio_header *hdr,
1443 		struct nfs_fattr *fattr)
1444 {
1445 	struct nfs_pgio_args *argp = &hdr->args;
1446 	struct nfs_pgio_res *resp = &hdr->res;
1447 	u64 size = argp->offset + resp->count;
1448 
1449 	if (!(fattr->valid & NFS_ATTR_FATTR_SIZE))
1450 		fattr->size = size;
1451 	if (nfs_size_to_loff_t(fattr->size) < i_size_read(hdr->inode)) {
1452 		fattr->valid &= ~NFS_ATTR_FATTR_SIZE;
1453 		return;
1454 	}
1455 	if (size != fattr->size)
1456 		return;
1457 	/* Set attribute barrier */
1458 	nfs_fattr_set_barrier(fattr);
1459 	/* ...and update size */
1460 	fattr->valid |= NFS_ATTR_FATTR_SIZE;
1461 }
1462 
1463 void nfs_writeback_update_inode(struct nfs_pgio_header *hdr)
1464 {
1465 	struct nfs_fattr *fattr = &hdr->fattr;
1466 	struct inode *inode = hdr->inode;
1467 
1468 	if (nfs_have_delegated_mtime(inode)) {
1469 		spin_lock(&inode->i_lock);
1470 		nfs_set_cache_invalid(inode, NFS_INO_INVALID_BLOCKS);
1471 		spin_unlock(&inode->i_lock);
1472 		return;
1473 	}
1474 
1475 	spin_lock(&inode->i_lock);
1476 	nfs_writeback_check_extend(hdr, fattr);
1477 	nfs_post_op_update_inode_force_wcc_locked(inode, fattr);
1478 	spin_unlock(&inode->i_lock);
1479 }
1480 EXPORT_SYMBOL_GPL(nfs_writeback_update_inode);
1481 
1482 /*
1483  * This function is called when the WRITE call is complete.
1484  */
1485 static int nfs_writeback_done(struct rpc_task *task,
1486 			      struct nfs_pgio_header *hdr,
1487 			      struct inode *inode)
1488 {
1489 	int status;
1490 
1491 	/*
1492 	 * ->write_done will attempt to use post-op attributes to detect
1493 	 * conflicting writes by other clients.  A strict interpretation
1494 	 * of close-to-open would allow us to continue caching even if
1495 	 * another writer had changed the file, but some applications
1496 	 * depend on tighter cache coherency when writing.
1497 	 */
1498 	status = NFS_PROTO(inode)->write_done(task, hdr);
1499 	if (status != 0)
1500 		return status;
1501 
1502 	nfs_add_stats(inode, NFSIOS_SERVERWRITTENBYTES, hdr->res.count);
1503 	trace_nfs_writeback_done(task, hdr);
1504 
1505 	if (task->tk_status >= 0) {
1506 		enum nfs3_stable_how committed = hdr->res.verf->committed;
1507 
1508 		if (committed == NFS_UNSTABLE) {
1509 			/*
1510 			 * We have some uncommitted data on the server at
1511 			 * this point, so ensure that we keep track of that
1512 			 * fact irrespective of what later writes do.
1513 			 */
1514 			set_bit(NFS_IOHDR_UNSTABLE_WRITES, &hdr->flags);
1515 		}
1516 
1517 		if (committed < hdr->args.stable) {
1518 			/* We tried a write call, but the server did not
1519 			 * commit data to stable storage even though we
1520 			 * requested it.
1521 			 * Note: There is a known bug in Tru64 < 5.0 in which
1522 			 *	 the server reports NFS_DATA_SYNC, but performs
1523 			 *	 NFS_FILE_SYNC. We therefore implement this checking
1524 			 *	 as a dprintk() in order to avoid filling syslog.
1525 			 */
1526 			static unsigned long    complain;
1527 
1528 			/* Note this will print the MDS for a DS write */
1529 			if (time_before(complain, jiffies)) {
1530 				dprintk("NFS:       faulty NFS server %s:"
1531 					" (committed = %d) != (stable = %d)\n",
1532 					NFS_SERVER(inode)->nfs_client->cl_hostname,
1533 					committed, hdr->args.stable);
1534 				complain = jiffies + 300 * HZ;
1535 			}
1536 		}
1537 	}
1538 
1539 	/* Deal with the suid/sgid bit corner case */
1540 	if (nfs_should_remove_suid(inode)) {
1541 		spin_lock(&inode->i_lock);
1542 		nfs_set_cache_invalid(inode, NFS_INO_INVALID_MODE
1543 				| NFS_INO_REVAL_FORCED);
1544 		spin_unlock(&inode->i_lock);
1545 	}
1546 	return 0;
1547 }
1548 
1549 /*
1550  * This function is called when the WRITE call is complete.
1551  */
1552 static void nfs_writeback_result(struct rpc_task *task,
1553 				 struct nfs_pgio_header *hdr)
1554 {
1555 	struct nfs_pgio_args	*argp = &hdr->args;
1556 	struct nfs_pgio_res	*resp = &hdr->res;
1557 
1558 	if (resp->count < argp->count && !list_empty(&hdr->pages)) {
1559 		static unsigned long    complain;
1560 		struct nfs_open_context *ctx =
1561 			hdr->req->wb_lock_context->open_context;
1562 
1563 		set_bit(NFS_CONTEXT_WRITE_SYNC, &ctx->flags);
1564 		/* This a short write! */
1565 		nfs_inc_stats(hdr->inode, NFSIOS_SHORTWRITE);
1566 
1567 		/* Has the server at least made some progress? */
1568 		if (resp->count == 0) {
1569 			if (time_before(complain, jiffies)) {
1570 				printk(KERN_WARNING
1571 				       "NFS: Server wrote zero bytes, expected %u.\n",
1572 				       argp->count);
1573 				complain = jiffies + 300 * HZ;
1574 			}
1575 			nfs_set_pgio_error(hdr, -EIO, argp->offset);
1576 			task->tk_status = -EIO;
1577 			return;
1578 		}
1579 
1580 		/* For non rpc-based layout drivers, retry-through-MDS */
1581 		if (!task->tk_ops) {
1582 			hdr->pnfs_error = -EAGAIN;
1583 			return;
1584 		}
1585 
1586 		/* Was this an NFSv2 write or an NFSv3 stable write? */
1587 		if (resp->verf->committed != NFS_UNSTABLE) {
1588 			/* Resend from where the server left off */
1589 			hdr->mds_offset += resp->count;
1590 			argp->offset += resp->count;
1591 			argp->pgbase += resp->count;
1592 			argp->count -= resp->count;
1593 		} else {
1594 			/* Resend as a stable write in order to avoid
1595 			 * headaches in the case of a server crash.
1596 			 */
1597 			argp->stable = NFS_FILE_SYNC;
1598 		}
1599 		resp->count = 0;
1600 		resp->verf->committed = 0;
1601 		rpc_restart_call_prepare(task);
1602 	}
1603 }
1604 
1605 static int wait_on_commit(struct nfs_mds_commit_info *cinfo)
1606 {
1607 	return wait_var_event_killable(&cinfo->rpcs_out,
1608 				       !atomic_read(&cinfo->rpcs_out));
1609 }
1610 
1611 void nfs_commit_begin(struct nfs_mds_commit_info *cinfo)
1612 {
1613 	atomic_inc(&cinfo->rpcs_out);
1614 }
1615 
1616 bool nfs_commit_end(struct nfs_mds_commit_info *cinfo)
1617 {
1618 	if (atomic_dec_and_test(&cinfo->rpcs_out)) {
1619 		wake_up_var(&cinfo->rpcs_out);
1620 		return true;
1621 	}
1622 	return false;
1623 }
1624 
1625 void nfs_commitdata_release(struct nfs_commit_data *data)
1626 {
1627 	put_nfs_open_context(data->context);
1628 	nfs_commit_free(data);
1629 }
1630 EXPORT_SYMBOL_GPL(nfs_commitdata_release);
1631 
1632 int nfs_initiate_commit(struct rpc_clnt *clnt, struct nfs_commit_data *data,
1633 			const struct nfs_rpc_ops *nfs_ops,
1634 			const struct rpc_call_ops *call_ops,
1635 			int how, int flags,
1636 			struct nfsd_file *localio)
1637 {
1638 	struct rpc_task *task;
1639 	int priority = flush_task_priority(how);
1640 	struct rpc_message msg = {
1641 		.rpc_argp = &data->args,
1642 		.rpc_resp = &data->res,
1643 		.rpc_cred = data->cred,
1644 	};
1645 	struct rpc_task_setup task_setup_data = {
1646 		.task = &data->task,
1647 		.rpc_client = clnt,
1648 		.rpc_message = &msg,
1649 		.callback_ops = call_ops,
1650 		.callback_data = data,
1651 		.workqueue = nfsiod_workqueue,
1652 		.flags = RPC_TASK_ASYNC | flags,
1653 		.priority = priority,
1654 	};
1655 
1656 	if (nfs_server_capable(data->inode, NFS_CAP_MOVEABLE))
1657 		task_setup_data.flags |= RPC_TASK_MOVEABLE;
1658 
1659 	/* Set up the initial task struct.  */
1660 	nfs_ops->commit_setup(data, &msg, &task_setup_data.rpc_client);
1661 	trace_nfs_initiate_commit(data);
1662 
1663 	dprintk("NFS: initiated commit call\n");
1664 
1665 	if (localio)
1666 		return nfs_local_commit(localio, data, call_ops);
1667 
1668 	task = rpc_run_task(&task_setup_data);
1669 	if (IS_ERR(task))
1670 		return PTR_ERR(task);
1671 	if (how & FLUSH_SYNC)
1672 		rpc_wait_for_completion_task(task);
1673 	rpc_put_task(task);
1674 	return 0;
1675 }
1676 EXPORT_SYMBOL_GPL(nfs_initiate_commit);
1677 
1678 static loff_t nfs_get_lwb(struct list_head *head)
1679 {
1680 	loff_t lwb = 0;
1681 	struct nfs_page *req;
1682 
1683 	list_for_each_entry(req, head, wb_list)
1684 		if (lwb < (req_offset(req) + req->wb_bytes))
1685 			lwb = req_offset(req) + req->wb_bytes;
1686 
1687 	return lwb;
1688 }
1689 
1690 /*
1691  * Set up the argument/result storage required for the RPC call.
1692  */
1693 void nfs_init_commit(struct nfs_commit_data *data,
1694 		     struct list_head *head,
1695 		     struct pnfs_layout_segment *lseg,
1696 		     struct nfs_commit_info *cinfo)
1697 {
1698 	struct nfs_page *first;
1699 	struct nfs_open_context *ctx;
1700 	struct inode *inode;
1701 
1702 	/* Set up the RPC argument and reply structs
1703 	 * NB: take care not to mess about with data->commit et al. */
1704 
1705 	if (head)
1706 		list_splice_init(head, &data->pages);
1707 
1708 	first = nfs_list_entry(data->pages.next);
1709 	ctx = nfs_req_openctx(first);
1710 	inode = d_inode(ctx->dentry);
1711 
1712 	data->inode	  = inode;
1713 	data->cred	  = ctx->cred;
1714 	data->lseg	  = lseg; /* reference transferred */
1715 	/* only set lwb for pnfs commit */
1716 	if (lseg)
1717 		data->lwb = nfs_get_lwb(&data->pages);
1718 	data->mds_ops     = &nfs_commit_ops;
1719 	data->completion_ops = cinfo->completion_ops;
1720 	data->dreq	  = cinfo->dreq;
1721 
1722 	data->args.fh     = NFS_FH(data->inode);
1723 	/* Note: we always request a commit of the entire inode */
1724 	data->args.offset = 0;
1725 	data->args.count  = 0;
1726 	data->context     = get_nfs_open_context(ctx);
1727 	data->res.fattr   = &data->fattr;
1728 	data->res.verf    = &data->verf;
1729 	nfs_fattr_init(&data->fattr);
1730 	nfs_commit_begin(cinfo->mds);
1731 }
1732 EXPORT_SYMBOL_GPL(nfs_init_commit);
1733 
1734 void nfs_retry_commit(struct list_head *page_list,
1735 		      struct pnfs_layout_segment *lseg,
1736 		      struct nfs_commit_info *cinfo,
1737 		      u32 ds_commit_idx)
1738 {
1739 	struct nfs_page *req;
1740 
1741 	while (!list_empty(page_list)) {
1742 		req = nfs_list_entry(page_list->next);
1743 		nfs_list_remove_request(req);
1744 		nfs_mark_request_commit(req, lseg, cinfo, ds_commit_idx);
1745 		nfs_folio_clear_commit(req);
1746 		nfs_unlock_and_release_request(req);
1747 	}
1748 }
1749 EXPORT_SYMBOL_GPL(nfs_retry_commit);
1750 
1751 static void nfs_commit_resched_write(struct nfs_commit_info *cinfo,
1752 				     struct nfs_page *req)
1753 {
1754 	struct folio *folio = nfs_page_to_folio(req);
1755 
1756 	filemap_dirty_folio(folio_mapping(folio), folio);
1757 }
1758 
1759 /*
1760  * Commit dirty pages
1761  */
1762 static int
1763 nfs_commit_list(struct inode *inode, struct list_head *head, int how,
1764 		struct nfs_commit_info *cinfo)
1765 {
1766 	struct nfs_commit_data	*data;
1767 	struct nfsd_file *localio;
1768 	unsigned short task_flags = 0;
1769 
1770 	/* another commit raced with us */
1771 	if (list_empty(head))
1772 		return 0;
1773 
1774 	data = nfs_commitdata_alloc();
1775 	if (!data) {
1776 		nfs_retry_commit(head, NULL, cinfo, -1);
1777 		return -ENOMEM;
1778 	}
1779 
1780 	/* Set up the argument struct */
1781 	nfs_init_commit(data, head, NULL, cinfo);
1782 	if (NFS_SERVER(inode)->nfs_client->cl_minorversion)
1783 		task_flags = RPC_TASK_MOVEABLE;
1784 
1785 	localio = nfs_local_open_fh(NFS_SERVER(inode)->nfs_client, data->cred,
1786 				    data->args.fh, &data->context->nfl,
1787 				    data->context->mode);
1788 	return nfs_initiate_commit(NFS_CLIENT(inode), data, NFS_PROTO(inode),
1789 				   data->mds_ops, how,
1790 				   RPC_TASK_CRED_NOREF | task_flags, localio);
1791 }
1792 
1793 /*
1794  * COMMIT call returned
1795  */
1796 static void nfs_commit_done(struct rpc_task *task, void *calldata)
1797 {
1798 	struct nfs_commit_data	*data = calldata;
1799 
1800 	/* Call the NFS version-specific code */
1801 	NFS_PROTO(data->inode)->commit_done(task, data);
1802 	trace_nfs_commit_done(task, data);
1803 }
1804 
1805 static void nfs_commit_release_pages(struct nfs_commit_data *data)
1806 {
1807 	const struct nfs_writeverf *verf = data->res.verf;
1808 	struct nfs_page	*req;
1809 	int status = data->task.tk_status;
1810 	struct nfs_commit_info cinfo;
1811 	struct folio *folio;
1812 
1813 	while (!list_empty(&data->pages)) {
1814 		req = nfs_list_entry(data->pages.next);
1815 		nfs_list_remove_request(req);
1816 		folio = nfs_page_to_folio(req);
1817 		nfs_folio_clear_commit(req);
1818 
1819 		dprintk("NFS:       commit (%s/%llu %d@%lld)",
1820 			nfs_req_openctx(req)->dentry->d_sb->s_id,
1821 			(unsigned long long)d_inode(nfs_req_openctx(req)->dentry)->i_ino,
1822 			req->wb_bytes,
1823 			(long long)req_offset(req));
1824 		if (status < 0) {
1825 			if (folio) {
1826 				trace_nfs_commit_error(data->inode, req,
1827 						       status);
1828 				nfs_mapping_set_error(folio, status);
1829 				nfs_inode_remove_request(req);
1830 			}
1831 			dprintk(", error = %d\n", status);
1832 			goto next;
1833 		}
1834 
1835 		/* Okay, COMMIT succeeded, apparently. Check the verifier
1836 		 * returned by the server against all stored verfs. */
1837 		if (nfs_write_match_verf(verf, req)) {
1838 			/* We have a match */
1839 			if (folio)
1840 				nfs_inode_remove_request(req);
1841 			dprintk(" OK\n");
1842 			goto next;
1843 		}
1844 		/* We have a mismatch. Write the page again */
1845 		dprintk(" mismatch\n");
1846 		nfs_mark_request_dirty(req);
1847 		set_bit(NFS_CONTEXT_WRITE_SYNC,
1848 			&req->wb_lock_context->open_context->flags);
1849 		atomic_long_inc(&NFS_I(data->inode)->redirtied_pages);
1850 	next:
1851 		nfs_unlock_and_release_request(req);
1852 		/* Latency breaker */
1853 		cond_resched();
1854 	}
1855 
1856 	nfs_init_cinfo(&cinfo, data->inode, data->dreq);
1857 	nfs_commit_end(cinfo.mds);
1858 }
1859 
1860 static void nfs_commit_release(void *calldata)
1861 {
1862 	struct nfs_commit_data *data = calldata;
1863 
1864 	data->completion_ops->completion(data);
1865 	nfs_commitdata_release(calldata);
1866 }
1867 
1868 static const struct rpc_call_ops nfs_commit_ops = {
1869 	.rpc_call_prepare = nfs_commit_prepare,
1870 	.rpc_call_done = nfs_commit_done,
1871 	.rpc_release = nfs_commit_release,
1872 };
1873 
1874 static const struct nfs_commit_completion_ops nfs_commit_completion_ops = {
1875 	.completion = nfs_commit_release_pages,
1876 	.resched_write = nfs_commit_resched_write,
1877 };
1878 
1879 int nfs_generic_commit_list(struct inode *inode, struct list_head *head,
1880 			    int how, struct nfs_commit_info *cinfo)
1881 {
1882 	int status;
1883 
1884 	status = pnfs_commit_list(inode, head, how, cinfo);
1885 	if (status == PNFS_NOT_ATTEMPTED)
1886 		status = nfs_commit_list(inode, head, how, cinfo);
1887 	return status;
1888 }
1889 
1890 static int __nfs_commit_inode(struct inode *inode, int how,
1891 		struct writeback_control *wbc)
1892 {
1893 	LIST_HEAD(head);
1894 	struct nfs_commit_info cinfo;
1895 	int may_wait = how & FLUSH_SYNC;
1896 	int ret, nscan;
1897 
1898 	how &= ~FLUSH_SYNC;
1899 	nfs_init_cinfo_from_inode(&cinfo, inode);
1900 	nfs_commit_begin(cinfo.mds);
1901 	for (;;) {
1902 		ret = nscan = nfs_scan_commit(inode, &head, &cinfo);
1903 		if (ret <= 0)
1904 			break;
1905 		ret = nfs_generic_commit_list(inode, &head, how, &cinfo);
1906 		if (ret < 0)
1907 			break;
1908 		ret = 0;
1909 		if (wbc && wbc->sync_mode == WB_SYNC_NONE) {
1910 			if (nscan < wbc->nr_to_write)
1911 				wbc->nr_to_write -= nscan;
1912 			else
1913 				wbc->nr_to_write = 0;
1914 		}
1915 		if (nscan < INT_MAX)
1916 			break;
1917 		cond_resched();
1918 	}
1919 	nfs_commit_end(cinfo.mds);
1920 	if (ret || !may_wait)
1921 		return ret;
1922 	return wait_on_commit(cinfo.mds);
1923 }
1924 
1925 int nfs_commit_inode(struct inode *inode, int how)
1926 {
1927 	return __nfs_commit_inode(inode, how, NULL);
1928 }
1929 EXPORT_SYMBOL_GPL(nfs_commit_inode);
1930 
1931 int nfs_write_inode(struct inode *inode, struct writeback_control *wbc)
1932 {
1933 	struct nfs_inode *nfsi = NFS_I(inode);
1934 	int flags = FLUSH_SYNC;
1935 	int ret = 0;
1936 
1937 	if (wbc->sync_mode == WB_SYNC_NONE) {
1938 		/* no commits means nothing needs to be done */
1939 		if (!atomic_long_read(&nfsi->commit_info.ncommit))
1940 			goto check_requests_outstanding;
1941 
1942 		/* Don't commit yet if this is a non-blocking flush and there
1943 		 * are a lot of outstanding writes for this mapping.
1944 		 */
1945 		if (mapping_tagged(inode->i_mapping, PAGECACHE_TAG_WRITEBACK))
1946 			goto out_mark_dirty;
1947 
1948 		/* don't wait for the COMMIT response */
1949 		flags = 0;
1950 	}
1951 
1952 	ret = __nfs_commit_inode(inode, flags, wbc);
1953 	if (!ret) {
1954 		if (flags & FLUSH_SYNC)
1955 			return 0;
1956 	} else if (atomic_long_read(&nfsi->commit_info.ncommit))
1957 		goto out_mark_dirty;
1958 
1959 check_requests_outstanding:
1960 	if (!atomic_read(&nfsi->commit_info.rpcs_out))
1961 		return ret;
1962 out_mark_dirty:
1963 	__mark_inode_dirty(inode, I_DIRTY_DATASYNC);
1964 	return ret;
1965 }
1966 EXPORT_SYMBOL_GPL(nfs_write_inode);
1967 
1968 /*
1969  * Wrapper for filemap_write_and_wait_range()
1970  *
1971  * Needed for pNFS in order to ensure data becomes visible to the
1972  * client.
1973  */
1974 int nfs_filemap_write_and_wait_range(struct address_space *mapping,
1975 		loff_t lstart, loff_t lend)
1976 {
1977 	int ret;
1978 
1979 	ret = filemap_write_and_wait_range(mapping, lstart, lend);
1980 	if (ret == 0)
1981 		ret = pnfs_sync_inode(mapping->host, true);
1982 	return ret;
1983 }
1984 EXPORT_SYMBOL_GPL(nfs_filemap_write_and_wait_range);
1985 
1986 /*
1987  * flush the inode to disk.
1988  */
1989 int nfs_wb_all(struct inode *inode)
1990 {
1991 	int ret;
1992 
1993 	trace_nfs_writeback_inode_enter(inode);
1994 
1995 	ret = filemap_write_and_wait(inode->i_mapping);
1996 	if (ret)
1997 		goto out;
1998 	ret = nfs_commit_inode(inode, FLUSH_SYNC);
1999 	if (ret < 0)
2000 		goto out;
2001 	pnfs_sync_inode(inode, true);
2002 	ret = 0;
2003 
2004 out:
2005 	trace_nfs_writeback_inode_exit(inode, ret);
2006 	return ret;
2007 }
2008 EXPORT_SYMBOL_GPL(nfs_wb_all);
2009 
2010 int nfs_wb_folio_cancel(struct inode *inode, struct folio *folio)
2011 {
2012 	struct nfs_page *req;
2013 	int ret = 0;
2014 
2015 	folio_wait_writeback(folio);
2016 
2017 	/* blocking call to cancel all requests and join to a single (head)
2018 	 * request */
2019 	req = nfs_lock_and_join_requests(folio);
2020 
2021 	if (IS_ERR(req)) {
2022 		ret = PTR_ERR(req);
2023 	} else if (req) {
2024 		/* all requests from this folio have been cancelled by
2025 		 * nfs_lock_and_join_requests, so just remove the head
2026 		 * request from the inode / page_private pointer and
2027 		 * release it */
2028 		nfs_inode_remove_request(req);
2029 		nfs_unlock_and_release_request(req);
2030 		folio_cancel_dirty(folio);
2031 	}
2032 
2033 	return ret;
2034 }
2035 
2036 /**
2037  * nfs_wb_folio_reclaim - Write back all requests on one page
2038  * @inode: pointer to page
2039  * @folio: pointer to folio
2040  *
2041  * Assumes that the folio has been locked by the caller
2042  */
2043 int nfs_wb_folio_reclaim(struct inode *inode, struct folio *folio)
2044 {
2045 	loff_t range_start = folio_pos(folio);
2046 	size_t len = folio_size(folio);
2047 	struct writeback_control wbc = {
2048 		.sync_mode = WB_SYNC_ALL,
2049 		.nr_to_write = 0,
2050 		.range_start = range_start,
2051 		.range_end = range_start + len - 1,
2052 		.for_sync = 1,
2053 	};
2054 	int ret;
2055 
2056 	if (folio_test_writeback(folio))
2057 		return -EBUSY;
2058 	if (folio_clear_dirty_for_io(folio)) {
2059 		trace_nfs_writeback_folio_reclaim(inode, range_start, len);
2060 		ret = nfs_writepage_locked(folio, &wbc);
2061 		trace_nfs_writeback_folio_reclaim_done(inode, range_start, len,
2062 						       ret);
2063 		return ret;
2064 	}
2065 	nfs_commit_inode(inode, 0);
2066 	return 0;
2067 }
2068 
2069 /**
2070  * nfs_wb_folio - Write back all requests on one page
2071  * @inode: pointer to page
2072  * @folio: pointer to folio
2073  *
2074  * Assumes that the folio has been locked by the caller, and will
2075  * not unlock it.
2076  */
2077 int nfs_wb_folio(struct inode *inode, struct folio *folio)
2078 {
2079 	loff_t range_start = folio_pos(folio);
2080 	size_t len = folio_size(folio);
2081 	struct writeback_control wbc = {
2082 		.sync_mode = WB_SYNC_ALL,
2083 		.nr_to_write = 0,
2084 		.range_start = range_start,
2085 		.range_end = range_start + len - 1,
2086 	};
2087 	int ret;
2088 
2089 	trace_nfs_writeback_folio(inode, range_start, len);
2090 
2091 	for (;;) {
2092 		folio_wait_writeback(folio);
2093 		if (folio_clear_dirty_for_io(folio)) {
2094 			ret = nfs_writepage_locked(folio, &wbc);
2095 			if (ret < 0)
2096 				goto out_error;
2097 			continue;
2098 		}
2099 		ret = 0;
2100 		if (!folio_test_private(folio))
2101 			break;
2102 		ret = nfs_commit_inode(inode, FLUSH_SYNC);
2103 		if (ret < 0)
2104 			goto out_error;
2105 	}
2106 out_error:
2107 	trace_nfs_writeback_folio_done(inode, range_start, len, ret);
2108 	return ret;
2109 }
2110 
2111 #ifdef CONFIG_MIGRATION
2112 int nfs_migrate_folio(struct address_space *mapping, struct folio *dst,
2113 		struct folio *src, enum migrate_mode mode)
2114 {
2115 	/*
2116 	 * If the private flag is set, the folio is currently associated with
2117 	 * an in-progress read or write request. Don't try to migrate it.
2118 	 *
2119 	 * FIXME: we could do this in principle, but we'll need a way to ensure
2120 	 *        that we can safely release the inode reference while holding
2121 	 *        the folio lock.
2122 	 */
2123 	if (folio_test_private(src)) {
2124 		if (mode == MIGRATE_SYNC)
2125 			nfs_wb_folio(src->mapping->host, src);
2126 		if (folio_test_private(src))
2127 			return -EBUSY;
2128 	}
2129 
2130 	if (folio_test_private_2(src)) { /* [DEPRECATED] */
2131 		if (mode == MIGRATE_ASYNC)
2132 			return -EBUSY;
2133 		folio_wait_private_2(src);
2134 	}
2135 
2136 	return migrate_folio(mapping, dst, src, mode);
2137 }
2138 #endif
2139 
2140 int __init nfs_init_writepagecache(void)
2141 {
2142 	nfs_wdata_cachep = kmem_cache_create("nfs_write_data",
2143 					     sizeof(struct nfs_pgio_header),
2144 					     0, SLAB_HWCACHE_ALIGN,
2145 					     NULL);
2146 	if (nfs_wdata_cachep == NULL)
2147 		return -ENOMEM;
2148 
2149 	nfs_wdata_mempool = mempool_create_slab_pool(MIN_POOL_WRITE,
2150 						     nfs_wdata_cachep);
2151 	if (nfs_wdata_mempool == NULL)
2152 		goto out_destroy_write_cache;
2153 
2154 	nfs_cdata_cachep = kmem_cache_create("nfs_commit_data",
2155 					     sizeof(struct nfs_commit_data),
2156 					     0, SLAB_HWCACHE_ALIGN,
2157 					     NULL);
2158 	if (nfs_cdata_cachep == NULL)
2159 		goto out_destroy_write_mempool;
2160 
2161 	nfs_commit_mempool = mempool_create_slab_pool(MIN_POOL_COMMIT,
2162 						      nfs_cdata_cachep);
2163 	if (nfs_commit_mempool == NULL)
2164 		goto out_destroy_commit_cache;
2165 
2166 	/*
2167 	 * NFS congestion size, scale with available memory.
2168 	 *
2169 	 *  64MB:    8192k
2170 	 * 128MB:   11585k
2171 	 * 256MB:   16384k
2172 	 * 512MB:   23170k
2173 	 *   1GB:   32768k
2174 	 *   2GB:   46340k
2175 	 *   4GB:   65536k
2176 	 *   8GB:   92681k
2177 	 *  16GB:  131072k
2178 	 *
2179 	 * This allows larger machines to have larger/more transfers.
2180 	 * Limit the default to 256M
2181 	 */
2182 	nfs_congestion_kb = (16*int_sqrt(totalram_pages())) << (PAGE_SHIFT-10);
2183 	if (nfs_congestion_kb > 256*1024)
2184 		nfs_congestion_kb = 256*1024;
2185 
2186 	return 0;
2187 
2188 out_destroy_commit_cache:
2189 	kmem_cache_destroy(nfs_cdata_cachep);
2190 out_destroy_write_mempool:
2191 	mempool_destroy(nfs_wdata_mempool);
2192 out_destroy_write_cache:
2193 	kmem_cache_destroy(nfs_wdata_cachep);
2194 	return -ENOMEM;
2195 }
2196 
2197 void nfs_destroy_writepagecache(void)
2198 {
2199 	mempool_destroy(nfs_commit_mempool);
2200 	kmem_cache_destroy(nfs_cdata_cachep);
2201 	mempool_destroy(nfs_wdata_mempool);
2202 	kmem_cache_destroy(nfs_wdata_cachep);
2203 }
2204 
2205 static const struct nfs_rw_ops nfs_rw_write_ops = {
2206 	.rw_alloc_header	= nfs_writehdr_alloc,
2207 	.rw_free_header		= nfs_writehdr_free,
2208 	.rw_done		= nfs_writeback_done,
2209 	.rw_result		= nfs_writeback_result,
2210 	.rw_initiate		= nfs_initiate_write,
2211 };
2212