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