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