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